EntryDAOSQLite.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_EntryDAOSQLite extends FreshRSS_EntryDAO {
  4. #[\Override]
  5. public static function isCompressed(): bool {
  6. return false;
  7. }
  8. #[\Override]
  9. public static function hasNativeHex(): bool {
  10. return false;
  11. }
  12. #[\Override]
  13. protected static function sqlConcat(string $s1, string $s2): string {
  14. return $s1 . '||' . $s2;
  15. }
  16. #[\Override]
  17. public static function sqlHexDecode(string $x): string {
  18. return $x;
  19. }
  20. #[\Override]
  21. public static function sqlIgnoreConflict(string $sql): string {
  22. return str_replace('INSERT INTO ', 'INSERT OR IGNORE INTO ', $sql);
  23. }
  24. #[\Override]
  25. protected static function sqlLimitAll(): string {
  26. // https://sqlite.org/lang_select.html#the_limit_clause
  27. return '-1';
  28. }
  29. #[\Override]
  30. public static function sqlRandom(): string {
  31. return 'RANDOM()';
  32. }
  33. #[\Override]
  34. protected static function sqlRegex(string $expression, string $regex, array &$values): string {
  35. $values[] = $regex;
  36. return "{$expression} REGEXP ?";
  37. }
  38. #[\Override]
  39. protected function registerSqlFunctions(string $sql): void {
  40. if (!str_contains($sql, ' REGEXP ')) {
  41. return;
  42. }
  43. // https://php.net/pdo.sqlitecreatefunction
  44. // https://www.sqlite.org/lang_expr.html#the_like_glob_regexp_match_and_extract_operators
  45. $this->pdo->sqliteCreateFunction('regexp',
  46. function (string $pattern, string $text): bool {
  47. return preg_match($pattern, $text) === 1;
  48. },
  49. 2
  50. );
  51. }
  52. /** @param array{0:string,1:int,2:string} $errorInfo */
  53. #[\Override]
  54. protected function autoUpdateDb(array $errorInfo): bool {
  55. if (($tableInfo = $this->pdo->query("PRAGMA table_info('entry')")) !== false && ($columns = $tableInfo->fetchAll(PDO::FETCH_COLUMN, 1)) !== false) {
  56. foreach (['attributes', 'lastUserModified', 'lastModified'] as $column) {
  57. if (!in_array($column, $columns, true)) {
  58. return $this->addColumn($column);
  59. }
  60. }
  61. }
  62. return false;
  63. }
  64. #[\Override]
  65. public function commitNewEntries(): bool {
  66. $sql = <<<'SQL'
  67. DROP TABLE IF EXISTS `tmp`;
  68. CREATE TEMP TABLE `tmp` AS
  69. SELECT id, guid, title, author, content, link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags, attributes
  70. FROM `_entrytmp`
  71. ORDER BY date, id;
  72. INSERT OR IGNORE INTO `_entry`
  73. (id, guid, title, author, content, link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags, attributes)
  74. SELECT rowid + (SELECT MAX(id) - COUNT(*) FROM `tmp`) AS id,
  75. guid, title, author, content, link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags, attributes
  76. FROM `tmp` t
  77. ORDER BY t.date, t.id;
  78. DELETE FROM `_entrytmp` WHERE id <= (SELECT MAX(id) FROM `tmp`);
  79. DROP TABLE IF EXISTS `tmp`;
  80. SQL;
  81. $hadTransaction = $this->pdo->inTransaction();
  82. if (!$hadTransaction) {
  83. $this->pdo->beginTransaction();
  84. }
  85. $result = $this->pdo->exec($sql) !== false;
  86. if (!$result) {
  87. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  88. }
  89. if (!$hadTransaction) {
  90. $this->pdo->commit();
  91. }
  92. return $result;
  93. }
  94. /**
  95. * Toggle the read marker on one or more article.
  96. * Then the cache is updated.
  97. *
  98. * @param numeric-string|array<numeric-string> $ids
  99. * @return int|false affected rows
  100. */
  101. #[\Override]
  102. public function markRead(array|string $ids, bool $is_read = true): int|false {
  103. if (is_array($ids)) { //Many IDs at once (used by API)
  104. //if (true) { //Speed heuristics //TODO: Not implemented yet for SQLite (so always call IDs one by one)
  105. $affected = 0;
  106. foreach ($ids as $id) {
  107. $affected += ($this->markRead($id, $is_read) ?: 0);
  108. }
  109. return $affected;
  110. //}
  111. } else {
  112. FreshRSS_UserDAO::touch();
  113. $this->pdo->beginTransaction();
  114. $sql = 'UPDATE `_entry` SET is_read=?, `lastUserModified` = ? WHERE id=? AND is_read=?';
  115. $values = [$is_read ? 1 : 0, time(), $ids, $is_read ? 0 : 1];
  116. $stm = $this->pdo->prepare($sql);
  117. if ($stm === false || !$stm->execute($values)) {
  118. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  119. /** @var array{0:string,1:int,2:string} $info */
  120. if ($this->autoUpdateDb($info)) {
  121. return $this->markRead($ids, $is_read);
  122. } else {
  123. Minz_Log::error('SQL error ' . __METHOD__ . ' A ' . json_encode($info));
  124. $this->pdo->rollBack();
  125. return false;
  126. }
  127. }
  128. $affected = $stm->rowCount();
  129. if ($affected > 0) {
  130. $sql = 'UPDATE `_feed` SET `cache_nbUnreads`=`cache_nbUnreads`' . ($is_read ? '-' : '+') . '1 '
  131. . 'WHERE id=(SELECT e.id_feed FROM `_entry` e WHERE e.id=?)';
  132. $values = [$ids];
  133. $stm = $this->pdo->prepare($sql);
  134. if ($stm === false || !$stm->execute($values)) {
  135. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  136. Minz_Log::error('SQL error ' . __METHOD__ . ' B ' . json_encode($info));
  137. $this->pdo->rollBack();
  138. return false;
  139. }
  140. }
  141. $this->pdo->commit();
  142. return $affected;
  143. }
  144. }
  145. /**
  146. * Mark all the articles in a tag as read.
  147. * @param int $id tag ID, or empty for targeting any tag
  148. * @param string $idMax max article ID
  149. * @return int|false affected rows
  150. */
  151. #[\Override]
  152. public function markReadTag(int $id = 0, string $idMax = '0', ?FreshRSS_BooleanSearch $filters = null, int $state = 0, bool $is_read = true): int|false {
  153. FreshRSS_UserDAO::touch();
  154. if ($idMax == 0) {
  155. $idMax = uTimeString();
  156. Minz_Log::debug('Calling markReadTag(0) is deprecated!');
  157. }
  158. $sql = 'UPDATE `_entry` SET is_read = ?, `lastUserModified` = ? WHERE is_read <> ? AND id <= ? AND '
  159. . 'id IN (SELECT et.id_entry FROM `_entrytag` et '
  160. . ($id == 0 ? '' : 'WHERE et.id_tag = ?')
  161. . ')';
  162. $values = [$is_read ? 1 : 0, time(), $is_read ? 1 : 0, $idMax];
  163. if ($id != 0) {
  164. $values[] = $id;
  165. }
  166. [$searchValues, $search] = $this->sqlListEntriesWhere(alias: 'e.', state: $state, filters: $filters);
  167. $stm = $this->pdo->prepare($sql . $search);
  168. if ($stm === false || !$stm->execute(array_merge($values, $searchValues))) {
  169. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  170. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  171. return false;
  172. }
  173. $affected = $stm->rowCount();
  174. if (($affected > 0) && (!$this->updateCacheUnreads(null, null))) {
  175. return false;
  176. }
  177. return $affected;
  178. }
  179. }