4
0

DatabaseDAO.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. public function size(bool $all = false): int {
  163. $db = FreshRSS_Context::systemConf()->db;
  164. // MariaDB does not refresh size information automatically
  165. $sql = <<<'SQL'
  166. ANALYZE TABLE `_category`, `_feed`, `_entry`, `_entrytmp`, `_tag`, `_entrytag`
  167. SQL;
  168. $stm = $this->pdo->query($sql);
  169. if ($stm !== false) {
  170. $stm->fetchAll();
  171. }
  172. //MySQL:
  173. $sql = <<<'SQL'
  174. SELECT SUM(DATA_LENGTH + INDEX_LENGTH + DATA_FREE)
  175. FROM information_schema.TABLES WHERE TABLE_SCHEMA=:table_schema
  176. SQL;
  177. $values = [':table_schema' => $db['base']];
  178. if (!$all) {
  179. $sql .= ' AND table_name LIKE :table_name';
  180. $values[':table_name'] = $this->pdo->prefix() . '%';
  181. }
  182. $res = $this->fetchColumn($sql, 0, $values);
  183. return isset($res[0]) ? (int)($res[0]) : -1;
  184. }
  185. public function optimize(): bool {
  186. $ok = true;
  187. $tables = ['category', 'feed', 'entry', 'entrytmp', 'tag', 'entrytag'];
  188. foreach ($tables as $table) {
  189. $sql = 'OPTIMIZE TABLE `_' . $table . '`'; //MySQL
  190. $stm = $this->pdo->query($sql);
  191. if ($stm == false || $stm->fetchAll(PDO::FETCH_ASSOC) == false) {
  192. $ok = false;
  193. $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
  194. Minz_Log::warning(__METHOD__ . ' error: ' . $sql . ' : ' . json_encode($info));
  195. }
  196. }
  197. return $ok;
  198. }
  199. public function minorDbMaintenance(): void {
  200. $catDAO = FreshRSS_Factory::createCategoryDao();
  201. $catDAO->resetDefaultCategoryName();
  202. include_once(APP_PATH . '/SQL/install.sql.' . $this->pdo->dbType() . '.php');
  203. if (!empty($GLOBALS['SQL_UPDATE_MINOR'])) {
  204. $sql = $GLOBALS['SQL_UPDATE_MINOR'];
  205. $isMariaDB = false;
  206. if ($this->pdo->dbType() === 'mysql') {
  207. $dbVersion = $this->fetchValue('SELECT version()') ?? '';
  208. $isMariaDB = stripos($dbVersion, 'MariaDB') !== false; // MariaDB includes its name in version, but not MySQL
  209. if (!$isMariaDB) {
  210. // MySQL does not support `DROP INDEX IF EXISTS` yet https://dev.mysql.com/doc/refman/8.3/en/drop-index.html
  211. // but MariaDB does https://mariadb.com/kb/en/drop-index/
  212. $sql = str_replace('DROP INDEX IF EXISTS', 'DROP INDEX', $sql);
  213. }
  214. }
  215. if ($this->pdo->exec($sql) === false) {
  216. $info = $this->pdo->errorInfo();
  217. if ($this->pdo->dbType() === 'mysql' &&
  218. !$isMariaDB && !empty($info[2]) && (stripos($info[2], "Can't DROP ") !== false)) {
  219. // Too bad for MySQL, but ignore error
  220. return;
  221. }
  222. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  223. }
  224. }
  225. }
  226. private static function stdError(string $error): bool {
  227. if (defined('STDERR')) {
  228. fwrite(STDERR, $error . "\n");
  229. }
  230. Minz_Log::error($error);
  231. return false;
  232. }
  233. public const SQLITE_EXPORT = 1;
  234. public const SQLITE_IMPORT = 2;
  235. public function dbCopy(string $filename, int $mode, bool $clearFirst = false, bool $verbose = true): bool {
  236. if (!extension_loaded('pdo_sqlite')) {
  237. return self::stdError('PHP extension pdo_sqlite is missing!');
  238. }
  239. $error = '';
  240. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  241. $userDAO = FreshRSS_Factory::createUserDao();
  242. $catDAO = FreshRSS_Factory::createCategoryDao();
  243. $feedDAO = FreshRSS_Factory::createFeedDao();
  244. $entryDAO = FreshRSS_Factory::createEntryDao();
  245. $tagDAO = FreshRSS_Factory::createTagDao();
  246. switch ($mode) {
  247. case self::SQLITE_EXPORT:
  248. if (@filesize($filename) > 0) {
  249. $error = 'Error: SQLite export file already exists: ' . $filename;
  250. }
  251. break;
  252. case self::SQLITE_IMPORT:
  253. if (!is_readable($filename)) {
  254. $error = 'Error: SQLite import file is not readable: ' . $filename;
  255. } elseif ($clearFirst) {
  256. $userDAO->deleteUser();
  257. $userDAO = FreshRSS_Factory::createUserDao();
  258. if ($this->pdo->dbType() === 'sqlite') {
  259. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  260. //SQLite is the only one with database-level optimization, instead of at table level.
  261. $this->optimize();
  262. }
  263. } else {
  264. if ($databaseDAO->exits()) {
  265. $nbEntries = $entryDAO->countUnreadRead();
  266. if (isset($nbEntries['all']) && $nbEntries['all'] > 0) {
  267. $error = 'Error: Destination database already contains some entries!';
  268. }
  269. }
  270. }
  271. break;
  272. default:
  273. $error = 'Invalid copy mode!';
  274. break;
  275. }
  276. if ($error != '') {
  277. return self::stdError($error);
  278. }
  279. $sqlite = null;
  280. try {
  281. $sqlite = new Minz_PdoSqlite('sqlite:' . $filename);
  282. $sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
  283. } catch (Exception $e) {
  284. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  285. return self::stdError($error);
  286. }
  287. Minz_ModelPdo::clean();
  288. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  289. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  290. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  291. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  292. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  293. switch ($mode) {
  294. case self::SQLITE_EXPORT:
  295. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  296. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  297. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  298. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  299. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  300. break;
  301. case self::SQLITE_IMPORT:
  302. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  303. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  304. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  305. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  306. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  307. break;
  308. default:
  309. return false;
  310. }
  311. $idMaps = [];
  312. if (defined('STDERR') && $verbose) {
  313. fwrite(STDERR, "Start SQL copy…\n");
  314. }
  315. $userTo->createUser();
  316. $catTo->beginTransaction();
  317. foreach ($catFrom->selectAll() as $category) {
  318. $cat = $catTo->searchByName($category['name']); //Useful for the default category
  319. if ($cat != null) {
  320. $catId = $cat->id();
  321. } else {
  322. $catId = $catTo->addCategory($category);
  323. if ($catId == false) {
  324. $error = 'Error during SQLite copy of categories!';
  325. return self::stdError($error);
  326. }
  327. }
  328. $idMaps['c' . $category['id']] = $catId;
  329. }
  330. foreach ($feedFrom->selectAll() as $feed) {
  331. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  332. $feedId = $feedTo->addFeed($feed);
  333. if ($feedId == false) {
  334. $error = 'Error during SQLite copy of feeds!';
  335. return self::stdError($error);
  336. }
  337. $idMaps['f' . $feed['id']] = $feedId;
  338. }
  339. $catTo->commit();
  340. $nbEntries = $entryFrom->count();
  341. $n = 0;
  342. $entryTo->beginTransaction();
  343. foreach ($entryFrom->selectAll() as $entry) {
  344. $n++;
  345. if (!empty($idMaps['f' . $entry['id_feed']])) {
  346. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  347. if (!$entryTo->addEntry($entry, false)) {
  348. $error = 'Error during SQLite copy of entries!';
  349. return self::stdError($error);
  350. }
  351. }
  352. if ($n % 100 === 1 && defined('STDERR') && $verbose) { //Display progression
  353. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries);
  354. }
  355. }
  356. if (defined('STDERR') && $verbose) {
  357. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . "\n");
  358. }
  359. $entryTo->commit();
  360. $feedTo->updateCachedValues();
  361. $idMaps = [];
  362. $tagTo->beginTransaction();
  363. foreach ($tagFrom->selectAll() as $tag) {
  364. $tagId = $tagTo->addTag($tag);
  365. if ($tagId == false) {
  366. $error = 'Error during SQLite copy of tags!';
  367. return self::stdError($error);
  368. }
  369. $idMaps['t' . $tag['id']] = $tagId;
  370. }
  371. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  372. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  373. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  374. if (!$tagTo->tagEntry($entryTag['id_tag'], $entryTag['id_entry'])) {
  375. $error = 'Error during SQLite copy of entry-tags!';
  376. return self::stdError($error);
  377. }
  378. }
  379. }
  380. $tagTo->commit();
  381. return true;
  382. }
  383. /**
  384. * Ensure that some PDO columns are `int` and not `string`.
  385. * Compatibility with PHP 7.
  386. * @param array<string|int|null> $table
  387. * @param array<string> $columns
  388. */
  389. public static function pdoInt(array &$table, array $columns): void {
  390. foreach ($columns as $column) {
  391. if (isset($table[$column]) && is_string($table[$column])) {
  392. $table[$column] = (int)$table[$column];
  393. }
  394. }
  395. }
  396. /**
  397. * Ensure that some PDO columns are `string` and not `bigint`.
  398. * @param array<string|int|null> $table
  399. * @param array<string> $columns
  400. */
  401. public static function pdoString(array &$table, array $columns): void {
  402. foreach ($columns as $column) {
  403. if (isset($table[$column])) {
  404. $table[$column] = (string)$table[$column];
  405. }
  406. }
  407. }
  408. }