DatabaseDAOSQLite.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This class is used to test database is well-constructed (SQLite).
  5. */
  6. class FreshRSS_DatabaseDAOSQLite extends FreshRSS_DatabaseDAO {
  7. public function tablesAreCorrect(): bool {
  8. $sql = 'SELECT name FROM sqlite_master WHERE type="table"';
  9. $stm = $this->pdo->query($sql);
  10. $res = $stm ? $stm->fetchAll(PDO::FETCH_ASSOC) : false;
  11. if ($res === false) {
  12. return false;
  13. }
  14. $tables = [
  15. $this->pdo->prefix() . 'category' => false,
  16. $this->pdo->prefix() . 'feed' => false,
  17. $this->pdo->prefix() . 'entry' => false,
  18. $this->pdo->prefix() . 'entrytmp' => false,
  19. $this->pdo->prefix() . 'tag' => false,
  20. $this->pdo->prefix() . 'entrytag' => false,
  21. ];
  22. foreach ($res as $value) {
  23. $tables[$value['name']] = true;
  24. }
  25. return count(array_keys($tables, true, true)) == count($tables);
  26. }
  27. /** @return array<array<string,string|int|bool|null>> */
  28. public function getSchema(string $table): array {
  29. $sql = 'PRAGMA table_info(' . $table . ')';
  30. $stm = $this->pdo->query($sql);
  31. return $stm ? $this->listDaoToSchema($stm->fetchAll(PDO::FETCH_ASSOC) ?: []) : [];
  32. }
  33. public function entryIsCorrect(): bool {
  34. return $this->checkTable('entry', [
  35. 'id', 'guid', 'title', 'author', 'content', 'link', 'date', 'lastSeen', 'hash', 'is_read', 'is_favorite', 'id_feed', 'tags',
  36. ]);
  37. }
  38. public function entrytmpIsCorrect(): bool {
  39. return $this->checkTable('entrytmp', [
  40. 'id', 'guid', 'title', 'author', 'content', 'link', 'date', 'lastSeen', 'hash', 'is_read', 'is_favorite', 'id_feed', 'tags'
  41. ]);
  42. }
  43. /**
  44. * @param array<string,string|int|bool|null> $dao
  45. * @return array{'name':string,'type':string,'notnull':bool,'default':mixed}
  46. */
  47. public function daoToSchema(array $dao): array {
  48. return [
  49. 'name' => (string)$dao['name'],
  50. 'type' => strtolower((string)$dao['type']),
  51. 'notnull' => $dao['notnull'] == '1' ? true : false,
  52. 'default' => $dao['dflt_value'],
  53. ];
  54. }
  55. public function size(bool $all = false): int {
  56. $sum = 0;
  57. if ($all) {
  58. foreach (glob(DATA_PATH . '/users/*/db.sqlite') ?: [] as $filename) {
  59. $sum += (@filesize($filename) ?: 0);
  60. }
  61. } else {
  62. $sum = (@filesize(DATA_PATH . '/users/' . $this->current_user . '/db.sqlite') ?: 0);
  63. }
  64. return $sum;
  65. }
  66. public function optimize(): bool {
  67. $ok = $this->pdo->exec('VACUUM') !== false;
  68. if (!$ok) {
  69. $info = $this->pdo->errorInfo();
  70. Minz_Log::warning(__METHOD__ . ' error : ' . json_encode($info));
  71. }
  72. return $ok;
  73. }
  74. }