DatabaseDAO.php 12 KB

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