DatabaseDAO.php 14 KB

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