EntryDAOPGSQL.php 2.1 KB

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