EntryDAOPGSQL.php 2.2 KB

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