dbupdater.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. class DbUpdater {
  3. private $dbh;
  4. private $db_type;
  5. private $need_version;
  6. function __construct($dbh, $db_type, $need_version) {
  7. $this->dbh = $dbh;
  8. $this->db_type = $db_type;
  9. $this->need_version = (int) $need_version;
  10. }
  11. function getSchemaVersion() {
  12. $result = db_query("SELECT schema_version FROM ttrss_version");
  13. return (int) db_fetch_result($result, 0, "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. return false;
  24. }
  25. }
  26. function performUpdateTo($version, $html_output = true) {
  27. if ($this->getSchemaVersion() == $version - 1) {
  28. $lines = $this->getSchemaLines($version);
  29. if (is_array($lines)) {
  30. db_query("BEGIN");
  31. foreach ($lines as $line) {
  32. if (strpos($line, "--") !== 0 && $line) {
  33. if (!db_query($line, false)) {
  34. if ($html_output) {
  35. print_notice("Query: $line");
  36. print_error("Error: " . db_last_query_error());
  37. } else {
  38. _debug("Query: $line");
  39. _debug("Error: " . db_last_query_error());
  40. }
  41. return false;
  42. }
  43. }
  44. }
  45. $db_version = $this->getSchemaVersion();
  46. if ($db_version == $version) {
  47. db_query("COMMIT");
  48. return true;
  49. } else {
  50. db_query("ROLLBACK");
  51. return false;
  52. }
  53. } else {
  54. return true;
  55. }
  56. } else {
  57. return false;
  58. }
  59. }
  60. }