DatabaseDAO.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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<string,string|int|bool|null>> */
  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<string,string|int|bool|null>>
  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']) && $this->pdo->exec($GLOBALS['SQL_UPDATE_MINOR']) === false) {
  204. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($this->pdo->errorInfo()));
  205. }
  206. }
  207. private static function stdError(string $error): bool {
  208. if (defined('STDERR')) {
  209. fwrite(STDERR, $error . "\n");
  210. }
  211. Minz_Log::error($error);
  212. return false;
  213. }
  214. public const SQLITE_EXPORT = 1;
  215. public const SQLITE_IMPORT = 2;
  216. public function dbCopy(string $filename, int $mode, bool $clearFirst = false): bool {
  217. if (!extension_loaded('pdo_sqlite')) {
  218. return self::stdError('PHP extension pdo_sqlite is missing!');
  219. }
  220. $error = '';
  221. $databaseDAO = FreshRSS_Factory::createDatabaseDAO();
  222. $userDAO = FreshRSS_Factory::createUserDao();
  223. $catDAO = FreshRSS_Factory::createCategoryDao();
  224. $feedDAO = FreshRSS_Factory::createFeedDao();
  225. $entryDAO = FreshRSS_Factory::createEntryDao();
  226. $tagDAO = FreshRSS_Factory::createTagDao();
  227. switch ($mode) {
  228. case self::SQLITE_EXPORT:
  229. if (@filesize($filename) > 0) {
  230. $error = 'Error: SQLite export file already exists: ' . $filename;
  231. }
  232. break;
  233. case self::SQLITE_IMPORT:
  234. if (!is_readable($filename)) {
  235. $error = 'Error: SQLite import file is not readable: ' . $filename;
  236. } elseif ($clearFirst) {
  237. $userDAO->deleteUser();
  238. $userDAO = FreshRSS_Factory::createUserDao();
  239. if ($this->pdo->dbType() === 'sqlite') {
  240. //We cannot just delete the .sqlite file otherwise PDO gets buggy.
  241. //SQLite is the only one with database-level optimization, instead of at table level.
  242. $this->optimize();
  243. }
  244. } else {
  245. if ($databaseDAO->exits()) {
  246. $nbEntries = $entryDAO->countUnreadRead();
  247. if (isset($nbEntries['all']) && $nbEntries['all'] > 0) {
  248. $error = 'Error: Destination database already contains some entries!';
  249. }
  250. }
  251. }
  252. break;
  253. default:
  254. $error = 'Invalid copy mode!';
  255. break;
  256. }
  257. if ($error != '') {
  258. return self::stdError($error);
  259. }
  260. $sqlite = null;
  261. try {
  262. $sqlite = new Minz_PdoSqlite('sqlite:' . $filename);
  263. } catch (Exception $e) {
  264. $error = 'Error while initialising SQLite copy: ' . $e->getMessage();
  265. return self::stdError($error);
  266. }
  267. Minz_ModelPdo::clean();
  268. $userDAOSQLite = new FreshRSS_UserDAO('', $sqlite);
  269. $categoryDAOSQLite = new FreshRSS_CategoryDAOSQLite('', $sqlite);
  270. $feedDAOSQLite = new FreshRSS_FeedDAOSQLite('', $sqlite);
  271. $entryDAOSQLite = new FreshRSS_EntryDAOSQLite('', $sqlite);
  272. $tagDAOSQLite = new FreshRSS_TagDAOSQLite('', $sqlite);
  273. switch ($mode) {
  274. case self::SQLITE_EXPORT:
  275. $userFrom = $userDAO; $userTo = $userDAOSQLite;
  276. $catFrom = $catDAO; $catTo = $categoryDAOSQLite;
  277. $feedFrom = $feedDAO; $feedTo = $feedDAOSQLite;
  278. $entryFrom = $entryDAO; $entryTo = $entryDAOSQLite;
  279. $tagFrom = $tagDAO; $tagTo = $tagDAOSQLite;
  280. break;
  281. case self::SQLITE_IMPORT:
  282. $userFrom = $userDAOSQLite; $userTo = $userDAO;
  283. $catFrom = $categoryDAOSQLite; $catTo = $catDAO;
  284. $feedFrom = $feedDAOSQLite; $feedTo = $feedDAO;
  285. $entryFrom = $entryDAOSQLite; $entryTo = $entryDAO;
  286. $tagFrom = $tagDAOSQLite; $tagTo = $tagDAO;
  287. break;
  288. default:
  289. return false;
  290. }
  291. $idMaps = [];
  292. if (defined('STDERR')) {
  293. fwrite(STDERR, "Start SQL copy…\n");
  294. }
  295. $userTo->createUser();
  296. $catTo->beginTransaction();
  297. foreach ($catFrom->selectAll() as $category) {
  298. $cat = $catTo->searchByName($category['name']); //Useful for the default category
  299. if ($cat != null) {
  300. $catId = $cat->id();
  301. } else {
  302. $catId = $catTo->addCategory($category);
  303. if ($catId == false) {
  304. $error = 'Error during SQLite copy of categories!';
  305. return self::stdError($error);
  306. }
  307. }
  308. $idMaps['c' . $category['id']] = $catId;
  309. }
  310. foreach ($feedFrom->selectAll() as $feed) {
  311. $feed['category'] = empty($idMaps['c' . $feed['category']]) ? FreshRSS_CategoryDAO::DEFAULTCATEGORYID : $idMaps['c' . $feed['category']];
  312. $feedId = $feedTo->addFeed($feed);
  313. if ($feedId == false) {
  314. $error = 'Error during SQLite copy of feeds!';
  315. return self::stdError($error);
  316. }
  317. $idMaps['f' . $feed['id']] = $feedId;
  318. }
  319. $catTo->commit();
  320. $nbEntries = $entryFrom->count();
  321. $n = 0;
  322. $entryTo->beginTransaction();
  323. foreach ($entryFrom->selectAll() as $entry) {
  324. $n++;
  325. if (!empty($idMaps['f' . $entry['id_feed']])) {
  326. $entry['id_feed'] = $idMaps['f' . $entry['id_feed']];
  327. if (!$entryTo->addEntry($entry, false)) {
  328. $error = 'Error during SQLite copy of entries!';
  329. return self::stdError($error);
  330. }
  331. }
  332. if ($n % 100 === 1 && defined('STDERR')) { //Display progression
  333. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries);
  334. }
  335. }
  336. if (defined('STDERR')) {
  337. fwrite(STDERR, "\033[0G" . $n . '/' . $nbEntries . "\n");
  338. }
  339. $entryTo->commit();
  340. $feedTo->updateCachedValues();
  341. $idMaps = [];
  342. $tagTo->beginTransaction();
  343. foreach ($tagFrom->selectAll() as $tag) {
  344. $tagId = $tagTo->addTag($tag);
  345. if ($tagId == false) {
  346. $error = 'Error during SQLite copy of tags!';
  347. return self::stdError($error);
  348. }
  349. $idMaps['t' . $tag['id']] = $tagId;
  350. }
  351. foreach ($tagFrom->selectEntryTag() as $entryTag) {
  352. if (!empty($idMaps['t' . $entryTag['id_tag']])) {
  353. $entryTag['id_tag'] = $idMaps['t' . $entryTag['id_tag']];
  354. if (!$tagTo->tagEntry($entryTag['id_tag'], $entryTag['id_entry'])) {
  355. $error = 'Error during SQLite copy of entry-tags!';
  356. return self::stdError($error);
  357. }
  358. }
  359. }
  360. $tagTo->commit();
  361. return true;
  362. }
  363. /**
  364. * Ensure that some PDO columns are `int` and not `string`.
  365. * Compatibility with PHP 7.
  366. * @param array<string|int|null> $table
  367. * @param array<string> $columns
  368. */
  369. public static function pdoInt(array &$table, array $columns): void {
  370. foreach ($columns as $column) {
  371. if (isset($table[$column]) && is_string($table[$column])) {
  372. $table[$column] = (int)$table[$column];
  373. }
  374. }
  375. }
  376. /**
  377. * Ensure that some PDO columns are `string` and not `bigint`.
  378. * @param array<string|int|null> $table
  379. * @param array<string> $columns
  380. */
  381. public static function pdoString(array &$table, array $columns): void {
  382. foreach ($columns as $column) {
  383. if (isset($table[$column])) {
  384. $table[$column] = (string)$table[$column];
  385. }
  386. }
  387. }
  388. }