DatabaseDAO.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This class is used to test database is well-constructed.
  5. */
  6. class FreshRSS_DatabaseDAO extends Minz_ModelPdo {
  7. //MySQL error codes
  8. public const ER_BAD_FIELD_ERROR = '42S22';
  9. public const ER_BAD_TABLE_ERROR = '42S02';
  10. public const ER_DATA_TOO_LONG = '1406';
  11. /**
  12. * Based on SQLite SQLITE_MAX_VARIABLE_NUMBER
  13. */
  14. public const MAX_VARIABLE_NUMBER = 998;
  15. //MySQL InnoDB maximum index length for UTF8MB4
  16. //https://dev.mysql.com/doc/refman/8.0/en/innodb-restrictions.html
  17. public const LENGTH_INDEX_UNICODE = 191;
  18. public function create(): string {
  19. require_once(APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php');
  20. $db = FreshRSS_Context::systemConf()->db;
  21. try {
  22. $sql = $GLOBALS['SQL_CREATE_DB'];
  23. if (!is_string($sql)) {
  24. throw new Exception('SQL_CREATE_DB is not a string!');
  25. }
  26. $sql = sprintf($sql, empty($db['base']) ? '' : $db['base']);
  27. return $this->pdo->exec($sql) === false ? 'Error during CREATE DATABASE' : '';
  28. } catch (Exception $e) {
  29. syslog(LOG_DEBUG, __METHOD__ . ' notice: ' . $e->getMessage());
  30. return $e->getMessage();
  31. }
  32. }
  33. public function testConnection(): string {
  34. try {
  35. $sql = 'SELECT 1';
  36. $stm = $this->pdo->query($sql);
  37. if ($stm === false) {
  38. return 'Error during SQL connection test!';
  39. }
  40. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  41. return $res == false ? 'Error during SQL connection fetch test!' : '';
  42. } catch (Exception $e) {
  43. syslog(LOG_DEBUG, __METHOD__ . ' warning: ' . $e->getMessage());
  44. return $e->getMessage();
  45. }
  46. }
  47. public function exits(): bool {
  48. $sql = 'SELECT * FROM `_entry` LIMIT 1';
  49. $stm = $this->pdo->query($sql);
  50. if ($stm !== false) {
  51. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  52. if ($res !== false) {
  53. return true;
  54. }
  55. }
  56. return false;
  57. }
  58. public function tablesAreCorrect(): bool {
  59. $res = $this->fetchAssoc('SHOW TABLES');
  60. if ($res == null) {
  61. return false;
  62. }
  63. $tables = [
  64. $this->pdo->prefix() . 'category' => false,
  65. $this->pdo->prefix() . 'feed' => false,
  66. $this->pdo->prefix() . 'entry' => false,
  67. $this->pdo->prefix() . 'entrytmp' => false,
  68. $this->pdo->prefix() . 'tag' => false,
  69. $this->pdo->prefix() . 'entrytag' => false,
  70. ];
  71. foreach ($res as $value) {
  72. $tables[array_pop($value)] = true;
  73. }
  74. return count(array_keys($tables, true, true)) === count($tables);
  75. }
  76. /** @return list<array{name:string,type:string,notnull:bool,default:mixed}> */
  77. public function getSchema(string $table): array {
  78. $res = $this->fetchAssoc('DESC `_' . $table . '`');
  79. return $res == null ? [] : $this->listDaoToSchema($res);
  80. }
  81. /** @param array<string> $schema */
  82. public function checkTable(string $table, array $schema): bool {
  83. $columns = $this->getSchema($table);
  84. if (count($columns) === 0 || count($schema) === 0) {
  85. return false;
  86. }
  87. $ok = count($columns) === count($schema);
  88. foreach ($columns as $c) {
  89. $ok &= in_array($c['name'], $schema, true);
  90. }
  91. return (bool)$ok;
  92. }
  93. public function categoryIsCorrect(): bool {
  94. return $this->checkTable('category', ['id', 'name']);
  95. }
  96. public function feedIsCorrect(): bool {
  97. return $this->checkTable('feed', [
  98. 'id',
  99. 'url',
  100. 'category',
  101. 'name',
  102. 'website',
  103. 'description',
  104. 'lastUpdate',
  105. 'priority',
  106. 'pathEntries',
  107. 'httpAuth',
  108. 'error',
  109. 'ttl',
  110. 'attributes',
  111. 'cache_nbEntries',
  112. 'cache_nbUnreads',
  113. ]);
  114. }
  115. public function entryIsCorrect(): bool {
  116. return $this->checkTable('entry', [
  117. 'id',
  118. 'guid',
  119. 'title',
  120. 'author',
  121. 'content_bin',
  122. 'link',
  123. 'date',
  124. 'lastSeen',
  125. 'hash',
  126. 'is_read',
  127. 'is_favorite',
  128. 'id_feed',
  129. 'tags',
  130. ]);
  131. }
  132. public function entrytmpIsCorrect(): bool {
  133. return $this->checkTable('entrytmp', [
  134. 'id', 'guid', 'title', 'author', 'content_bin', 'link', 'date', 'lastSeen', 'hash', 'is_read', 'is_favorite', 'id_feed', 'tags'
  135. ]);
  136. }
  137. public function tagIsCorrect(): bool {
  138. return $this->checkTable('tag', ['id', 'name', 'attributes']);
  139. }
  140. public function entrytagIsCorrect(): bool {
  141. return $this->checkTable('entrytag', ['id_tag', 'id_entry']);
  142. }
  143. /**
  144. * @param array<string,string|int|bool|null> $dao
  145. * @return array{name:string,type:string,notnull:bool,default:mixed}
  146. */
  147. public function daoToSchema(array $dao): array {
  148. return [
  149. 'name' => is_string($dao['Field'] ?? null) ? $dao['Field'] : '',
  150. 'type' => is_string($dao['Type'] ?? null) ? strtolower($dao['Type']) : '',
  151. 'notnull' => empty($dao['Null']),
  152. 'default' => is_scalar($dao['Default'] ?? null) ? $dao['Default'] : null,
  153. ];
  154. }
  155. /**
  156. * @param array<array<string,string|int|bool|null>> $listDAO
  157. * @return list<array{name:string,type:string,notnull:bool,default:mixed}>
  158. */
  159. public function listDaoToSchema(array $listDAO): array {
  160. $list = [];
  161. foreach ($listDAO as $dao) {
  162. $list[] = $this->daoToSchema($dao);
  163. }
  164. return $list;
  165. }
  166. private static ?string $staticVersion = null;
  167. /**
  168. * To override the database version. Useful for testing.
  169. */
  170. public static function setStaticVersion(?string $version): void {
  171. self::$staticVersion = $version;
  172. }
  173. protected function selectVersion(): string {
  174. return $this->fetchValue('SELECT version()') ?? '';
  175. }
  176. public function version(): string {
  177. if (self::$staticVersion !== null) {
  178. return self::$staticVersion;
  179. }
  180. static $version = null;
  181. if (!is_string($version)) {
  182. $version = $this->selectVersion();
  183. }
  184. return $version;
  185. }
  186. public function pdoClientVersion(): string {
  187. $version = $this->pdo->getAttribute(PDO::ATTR_CLIENT_VERSION);
  188. return is_string($version) ? $version : '';
  189. }
  190. final public function isMariaDB(): bool {
  191. // MariaDB includes its name in version, but not MySQL
  192. return str_contains($this->version(), 'MariaDB');
  193. }
  194. /**
  195. * @return bool true if the database PDO driver returns typed integer values as it should, false otherwise.
  196. */
  197. final public function testTyping(): bool {
  198. $sql = 'SELECT 2 + 3';
  199. if (($stm = $this->pdo->query($sql)) !== false) {
  200. $res = $stm->fetchAll(PDO::FETCH_COLUMN, 0);
  201. return ($res[0] ?? null) === 5;
  202. }
  203. return false;
  204. }
  205. public function size(bool $all = false): int {
  206. $db = FreshRSS_Context::systemConf()->db;
  207. // MariaDB does not refresh size information automatically
  208. $sql = <<<'SQL'
  209. ANALYZE TABLE `_category`, `_feed`, `_entry`, `_entrytmp`, `_tag`, `_entrytag`
  210. SQL;
  211. $stm = $this->pdo->query($sql);
  212. if ($stm !== false) {
  213. $stm->fetchAll();
  214. }
  215. //MySQL:
  216. $sql = <<<'SQL'
  217. SELECT SUM(DATA_LENGTH + INDEX_LENGTH + DATA_FREE)
  218. FROM information_schema.TABLES WHERE TABLE_SCHEMA=:table_schema
  219. SQL;
  220. $values = [':table_schema' => $db['base']];
  221. if (!$all) {
  222. $sql .= ' AND table_name LIKE :table_name';
  223. $values[':table_name'] = $this->pdo->prefix() . '%';
  224. }
  225. $res = $this->fetchColumn($sql, 0, $values);
  226. return isset($res[0]) ? (int)($res[0]) : -1;
  227. }
  228. public function optimize(): bool {
  229. $ok = true;
  230. $tables = ['category', 'feed', 'entry', 'entrytmp', 'tag', 'entrytag'];
  231. foreach ($tables as $table) {
  232. $sql = 'OPTIMIZE TABLE `_' . $table . '`'; //MySQL
  233. $stm = $this->pdo->query($sql);
  234. if ($stm === false || $stm->fetchAll(PDO::FETCH_ASSOC) == false) {
  235. $ok = false;
  236. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  237. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  238. }
  239. }
  240. return $ok;
  241. }
  242. public function minorDbMaintenance(): void {
  243. $catDAO = FreshRSS_Factory::createCategoryDao();
  244. $catDAO->resetDefaultCategoryName();
  245. include_once(APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php');
  246. if (!empty($GLOBALS['SQL_UPDATE_MINOR']) && is_string($GLOBALS['SQL_UPDATE_MINOR'])) {
  247. $sql = $GLOBALS['SQL_UPDATE_MINOR'];
  248. $isMariaDB = false;
  249. if ($this->pdo->dbType() === 'mysql') {
  250. $isMariaDB = $this->isMariaDB();
  251. if (!$isMariaDB) {
  252. // MySQL does not support `DROP INDEX IF EXISTS` yet https://dev.mysql.com/doc/refman/8.3/en/drop-index.html
  253. // but MariaDB does https://mariadb.com/kb/en/drop-index/
  254. $sql = str_replace('DROP INDEX IF EXISTS', 'DROP INDEX', $sql);
  255. }
  256. }
  257. if ($this->pdo->exec($sql) === false) {
  258. $info = $this->pdo->errorInfo();
  259. if ($this->pdo->dbType() === 'mysql' &&
  260. !$isMariaDB && is_string($info[2] ?? null) && (stripos($info[2], "Can't DROP ") !== false)) {
  261. // Too bad for MySQL, but ignore error
  262. return;
  263. }
  264. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  265. }
  266. }
  267. }
  268. private static function stdError(string $error): bool {
  269. if (defined('STDERR')) {
  270. fwrite(STDERR, $error . "\n");
  271. }
  272. Minz_Log::error($error);
  273. return false;
  274. }
  275. public const SQLITE_EXPORT = 1;
  276. public const SQLITE_IMPORT = 2;
  277. public function dbCopy(string $filename, int $mode, bool $clearFirst = false, bool $verbose = true): bool {
  278. if (!extension_loaded('pdo_sqlite')) {
  279. return self::stdError('PHP extension pdo_sqlite is missing!');
  280. }
  281. $error = '';
  282. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  283. $userDAO = FreshRSS_Factory::createUserDao();
  284. $catDAO = FreshRSS_Factory::createCategoryDao();
  285. $feedDAO = FreshRSS_Factory::createFeedDao();
  286. $entryDAO = FreshRSS_Factory::createEntryDao();
  287. $tagDAO = FreshRSS_Factory::createTagDao();
  288. switch ($mode) {
  289. case self::SQLITE_EXPORT:
  290. if (@filesize($filename) > 0) {
  291. $error = 'Error: SQLite export file already exists: ' . $filename;
  292. }
  293. break;
  294. case self::SQLITE_IMPORT:
  295. if (!is_readable($filename)) {
  296. $error = 'Error: SQLite import file is not readable: ' . $filename;
  297. } elseif ($clearFirst) {
  298. $userDAO->deleteUser();
  299. $userDAO = FreshRSS_Factory::createUserDao();
  300. if ($this->pdo->dbType() === 'sqlite') {
  301. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  302. //SQLite is the only one with database-level optimization, instead of at table level.
  303. $this->optimize();
  304. }
  305. } else {
  306. if ($databaseDAO->exits()) {
  307. $nbEntries = $entryDAO->countUnreadRead();
  308. if (isset($nbEntries['all']) && $nbEntries['all'] > 0) {
  309. $error = 'Error: Destination database already contains some entries!';
  310. }
  311. }
  312. }
  313. break;
  314. default:
  315. $error = 'Invalid copy mode!';
  316. break;
  317. }
  318. if ($error != '') {
  319. return self::stdError($error);
  320. }
  321. $sqlite = null;
  322. try {
  323. $sqlite = new Minz_PdoSqlite('sqlite:' . $filename);
  324. $sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
  325. } catch (Exception $e) {
  326. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  327. return self::stdError($error);
  328. }
  329. Minz_ModelPdo::clean();
  330. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  331. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  332. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  333. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  334. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  335. switch ($mode) {
  336. case self::SQLITE_EXPORT:
  337. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  338. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  339. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  340. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  341. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  342. break;
  343. case self::SQLITE_IMPORT:
  344. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  345. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  346. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  347. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  348. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  349. break;
  350. default:
  351. return false;
  352. }
  353. $idMaps = [];
  354. if (defined('STDERR') && $verbose) {
  355. fwrite(STDERR, "Start SQL copy…\n");
  356. }
  357. $userTo->createUser();
  358. $catTo->beginTransaction();
  359. foreach ($catFrom->selectAll() as $category) {
  360. $cat = $catTo->searchByName($category['name']); //Useful for the default category
  361. if ($cat != null) {
  362. $catId = $cat->id();
  363. } else {
  364. $catId = $catTo->addCategory($category);
  365. if ($catId == false) {
  366. $error = 'Error during SQLite copy of categories!';
  367. return self::stdError($error);
  368. }
  369. }
  370. $idMaps['c' . $category['id']] = $catId;
  371. }
  372. foreach ($feedFrom->selectAll() as $feed) {
  373. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  374. $feedId = $feedTo->addFeed($feed);
  375. if ($feedId == false) {
  376. $error = 'Error during SQLite copy of feeds!';
  377. return self::stdError($error);
  378. }
  379. $idMaps['f' . $feed['id']] = $feedId;
  380. }
  381. $catTo->commit();
  382. $nbEntries = $entryFrom->count();
  383. $n = 0;
  384. $entryTo->beginTransaction();
  385. foreach ($entryFrom->selectAll() as $entry) {
  386. $n++;
  387. if (!empty($idMaps['f' . $entry['id_feed']])) {
  388. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  389. if (!$entryTo->addEntry($entry, false)) {
  390. $error = 'Error during SQLite copy of entries!';
  391. return self::stdError($error);
  392. }
  393. }
  394. if ($n % 100 === 1 && defined('STDERR') && $verbose) { //Display progression
  395. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries);
  396. }
  397. }
  398. if (defined('STDERR') && $verbose) {
  399. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . "\n");
  400. }
  401. $entryTo->commit();
  402. $feedTo->updateCachedValues();
  403. $idMaps = [];
  404. $tagTo->beginTransaction();
  405. foreach ($tagFrom->selectAll() as $tag) {
  406. $tagId = $tagTo->addTag($tag);
  407. if ($tagId == false) {
  408. $error = 'Error during SQLite copy of tags!';
  409. return self::stdError($error);
  410. }
  411. $idMaps['t' . $tag['id']] = $tagId;
  412. }
  413. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  414. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  415. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  416. if (!$tagTo->tagEntry($entryTag['id_tag'], (string)$entryTag['id_entry'])) {
  417. $error = 'Error during SQLite copy of entry-tags!';
  418. return self::stdError($error);
  419. }
  420. }
  421. }
  422. $tagTo->commit();
  423. return true;
  424. }
  425. }