4
0

DatabaseDAO.php 13 KB

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