EntryDAOPGSQL.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. class FreshRSS_EntryDAOPGSQL extends FreshRSS_EntryDAOSQLite {
  3. public static function hasNativeHex(): bool {
  4. return true;
  5. }
  6. public static function sqlHexDecode(string $x): string {
  7. return 'decode(' . $x . ", 'hex')";
  8. }
  9. public static function sqlHexEncode(string $x): string {
  10. return 'encode(' . $x . ", 'hex')";
  11. }
  12. public static function sqlIgnoreConflict(string $sql): string {
  13. return rtrim($sql, ' ;') . ' ON CONFLICT DO NOTHING';
  14. }
  15. /** @param array<string> $errorInfo */
  16. protected function autoUpdateDb(array $errorInfo): bool {
  17. if (isset($errorInfo[0])) {
  18. if ($errorInfo[0] === FreshRSS_DatabaseDAO::ER_BAD_FIELD_ERROR || $errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_COLUMN) {
  19. $errorLines = explode("\n", $errorInfo[2], 2); // The relevant column name is on the first line, other lines are noise
  20. foreach (['attributes'] as $column) {
  21. if (stripos($errorLines[0], $column) !== false) {
  22. return $this->addColumn($column);
  23. }
  24. }
  25. }
  26. if ($errorInfo[0] === FreshRSS_DatabaseDAOPGSQL::UNDEFINED_TABLE) {
  27. if (stripos($errorInfo[2], 'tag') !== false) {
  28. $tagDAO = FreshRSS_Factory::createTagDao();
  29. return $tagDAO->createTagTable(); //v1.12.0
  30. } elseif (stripos($errorInfo[2], 'entrytmp') !== false) {
  31. return $this->createEntryTempTable(); //v1.7.0
  32. }
  33. }
  34. }
  35. return false;
  36. }
  37. public function commitNewEntries(): bool {
  38. //TODO: Update to PostgreSQL 9.5+ syntax with ON CONFLICT DO NOTHING
  39. $sql = 'DO $$
  40. DECLARE
  41. maxrank bigint := (SELECT MAX(id) FROM `_entrytmp`);
  42. rank bigint := (SELECT maxrank - COUNT(*) FROM `_entrytmp`);
  43. BEGIN
  44. INSERT INTO `_entry`
  45. (id, guid, title, author, content, link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags, attributes)
  46. (SELECT rank + row_number() OVER(ORDER BY date, id) AS id, guid, title, author, content,
  47. link, date, `lastSeen`, hash, is_read, is_favorite, id_feed, tags, attributes
  48. FROM `_entrytmp` AS etmp
  49. WHERE NOT EXISTS (
  50. SELECT 1 FROM `_entry` AS ereal
  51. WHERE (etmp.id = ereal.id) OR (etmp.id_feed = ereal.id_feed AND etmp.guid = ereal.guid))
  52. ORDER BY date, id);
  53. DELETE FROM `_entrytmp` WHERE id <= maxrank;
  54. END $$;';
  55. $hadTransaction = $this->pdo->inTransaction();
  56. if (!$hadTransaction) {
  57. $this->pdo->beginTransaction();
  58. }
  59. $result = $this->pdo->exec($sql) !== false;
  60. if (!$hadTransaction) {
  61. $this->pdo->commit();
  62. }
  63. return $result;
  64. }
  65. }