4
0

DatabaseDAO.php 13 KB

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