dbupdater.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. class DbUpdater {
  3. private $pdo;
  4. private $db_type;
  5. private $need_version;
  6. function __construct($pdo, $db_type, $need_version) {
  7. $this->pdo = Db::pdo(); //$pdo;
  8. $this->db_type = $db_type;
  9. $this->need_version = (int) $need_version;
  10. }
  11. function getSchemaVersion() {
  12. $row = $this->pdo->query("SELECT schema_version FROM ttrss_version")->fetch();
  13. return (int) $row['schema_version'];
  14. }
  15. function isUpdateRequired() {
  16. return $this->getSchemaVersion() < $this->need_version;
  17. }
  18. function getSchemaLines($version) {
  19. $filename = "schema/versions/".$this->db_type."/$version.sql";
  20. if (file_exists($filename)) {
  21. return explode(";", preg_replace("/[\r\n]/", "", file_get_contents($filename)));
  22. } else {
  23. user_error("DB Updater: schema file for version $version is not found.");
  24. return false;
  25. }
  26. }
  27. function performUpdateTo($version, $html_output = true) {
  28. if ($this->getSchemaVersion() == $version - 1) {
  29. $lines = $this->getSchemaLines($version);
  30. if (is_array($lines)) {
  31. $this->pdo->beginTransaction();
  32. foreach ($lines as $line) {
  33. if (strpos($line, "--") !== 0 && $line) {
  34. if (!$this->pdo->query($line)) {
  35. if ($html_output) {
  36. print_notice("Query: $line");
  37. print_error("Error: " . implode(", ", $this->pdo->errorInfo()));
  38. } else {
  39. _debug("Query: $line");
  40. _debug("Error: " . implode(", ", $this->pdo->errorInfo()));
  41. }
  42. return false;
  43. }
  44. }
  45. }
  46. $db_version = $this->getSchemaVersion();
  47. if ($db_version == $version) {
  48. $this->pdo->commit();
  49. return true;
  50. } else {
  51. $this->pdo->rollBack();
  52. return false;
  53. }
  54. } else {
  55. return false;
  56. }
  57. } else {
  58. return false;
  59. }
  60. }
  61. }