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