db.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. class Db
  3. {
  4. /* @var Db $instance */
  5. private static $instance;
  6. /* @var IDb $adapter */
  7. private $adapter;
  8. private $link;
  9. /* @var PDO $pdo */
  10. private $pdo;
  11. private function __clone() {
  12. //
  13. }
  14. private function legacy_connect() {
  15. user_error("Legacy connect requested to " . DB_TYPE, E_USER_NOTICE);
  16. $er = error_reporting(E_ALL);
  17. switch (DB_TYPE) {
  18. case "mysql":
  19. $this->adapter = new Db_Mysqli();
  20. break;
  21. case "pgsql":
  22. $this->adapter = new Db_Pgsql();
  23. break;
  24. default:
  25. die("Unknown DB_TYPE: " . DB_TYPE);
  26. }
  27. if (!$this->adapter) {
  28. print("Error initializing database adapter for " . DB_TYPE);
  29. exit(100);
  30. }
  31. $this->link = $this->adapter->connect(DB_HOST, DB_USER, DB_PASS, DB_NAME, defined('DB_PORT') ? DB_PORT : "");
  32. if (!$this->link) {
  33. print("Error connecting through adapter: " . $this->adapter->last_error());
  34. exit(101);
  35. }
  36. error_reporting($er);
  37. }
  38. private function pdo_connect() {
  39. $db_port = defined('DB_PORT') && DB_PORT ? ';port=' . DB_PORT : '';
  40. $db_host = defined('DB_HOST') && DB_HOST ? ';host=' . DB_HOST : '';
  41. $this->pdo = new PDO(DB_TYPE . ':dbname=' . DB_NAME . $db_host . $db_port,
  42. DB_USER,
  43. DB_PASS);
  44. if (!$this->pdo) {
  45. print("Error connecting via PDO.");
  46. exit(101);
  47. }
  48. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
  49. if (DB_TYPE == "pgsql") {
  50. $this->pdo->query("set client_encoding = 'UTF-8'");
  51. $this->pdo->query("set datestyle = 'ISO, european'");
  52. $this->pdo->query("set TIME ZONE 0");
  53. $this->pdo->query("set cpu_tuple_cost = 0.5");
  54. } else if (DB_TYPE == "mysql") {
  55. $this->pdo->query("SET time_zone = '+0:0'");
  56. if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) {
  57. $this->pdo->query("SET NAMES " . MYSQL_CHARSET);
  58. }
  59. }
  60. }
  61. public static function get() {
  62. if (self::$instance == null)
  63. self::$instance = new self();
  64. if (!self::$instance->adapter) {
  65. self::$instance->legacy_connect();
  66. }
  67. return self::$instance->adapter;
  68. }
  69. public static function pdo() {
  70. if (self::$instance == null)
  71. self::$instance = new self();
  72. if (!self::$instance->pdo) {
  73. self::$instance->pdo_connect();
  74. }
  75. return self::$instance->pdo;
  76. }
  77. }