summaryrefslogtreecommitdiff
path: root/include/PgDB.class.php
blob: b79b2ec89bc9cbed4020213b9b09ab22844630b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<?php
/**
 *
 * PgDB - future unified database access interface,
 * currently only wrapping some global functions
 */

// temporary workaround until new configuration framework will be in place.
class PgDB {
    static private $_db = null;
    static private $_master_db = null;
    static private $_slave_db = null;
    // counts how many times transaction has been started
    static private $_transaction_depth = 0;
    // states if current transaction has been rolled back at some point
    static private $_transaction_failed = false;

    static private $_config = null;

    static private $_me = null;

    /**
     * Private constructor prevents multiple objects creation.
     * Guarantees singleton pattern usage of class.
     */
    private function __construct() {
    }

    /**
     * returns object providing access to master database PDO functions
     * \return object behaving like PDO Database object
     */
    static function db() {
        self::_needsMasterDB();
        if (self::$_me == null) {
            self::$_me = new PgDB();
        }
        return self::$_me;
    }


    /**
     * Mapping method - thanks to it PgDB object behaves like PDO
     *
     * @param funcname PDO function to be mapped
     * @param args array of PDO function arguments
     * @return PDO function response
     */
    public function __call($funcname, $args) {
        return call_user_func_array([self::$_db,$funcname],$args);
    }

    /**
     * Declares database dependency, establishes connection if needed.
     * Guarantees availablility of master connection.
     */
    static private function _needsMasterDB() {
        self::$_db = &self::$_master_db;
        if (self::$_db == null) {
            self::_masterConnect();
        }
    }

    static private function _getConfig($key, $default = '') {
        if (self::$_config === NULL) {
            self::$_config = Env::get('db');
        }
        if (isset(self::$_config[$key])) {
            return self::$_config[$key];
        }
        return $default;
    }

    /**
     * Establishes connection to master server
     * (currently there's no multimaster support available).
     */
	static private function _masterConnect() {
        self::$_master_db = new PDO('pgsql:host='.self::_getConfig('host').';port='.self::_getConfig('port', 5432).';dbname='.self::_getConfig('database').'', self::_getConfig('user'), self::_getConfig('password'));
        self::$_master_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        self::$_db = &self::$_master_db;
	}

    /** returns value from first column of first row of query result.
     * accepts two types of variable substitution: '?' or ':var',
     * '?' expects variable parameter list, ':var' expects second argument
     * to be array working as dictionary
     * \param $query PgSQL query with optional parameter substitution
     * \param $params (optional) array or first parameter for '?' type query
     * \param $... - (optional) following parameters for '?' type query
     */
    public static function fetchValue($query, $params = []) {
        self::_needsMasterDB();
        $sth = self::$_db->prepare($query.';');
        if (!is_array($params)) {
            $params = array_slice(func_get_args(),1);
        }
        $sth->execute($params);
        $result = $sth->fetch(PDO::FETCH_NUM);
        return isset($result[0]) ? $result[0] : null;
    }

    /** returns first first row of query result as assiociative array.
     * accepts two types of variable substitution: '?' or ':var',
     * '?' expects variable parameter list, ':var' expects second argument
     * to be array working as dictionary
     * \param $query PgSQL query with optional parameter substitution
     * \param $params (optional) array or first parameter for '?' type query
     * \param $... - (optional) following parameters for '?' type query
     */
    public static function fetchRow($query, $params = []) {
        self::_needsMasterDB();
        $sth = self::$_db->prepare($query.';');
        if (!is_array($params)) {
            $params = array_slice(func_get_args(),1);
        }

        $sth->execute($params);
        return $sth->fetch(PDO::FETCH_ASSOC);
    }

    /** returns whole query result as numbered array of assiociative arrays.
     * accepts two types of variable substitution: '?' or ':var',
     * '?' expects variable parameter list, ':var' expects second argument
     * to be array working as dictionary
     * \param $query PgSQL query with optional parameter substitution
     * \param $params (optional) array or first parameter for '?' type query
     * \param $... - (optional) following parameters for '?' type query
     */
    static public function fetchAll($query, $params = []) {
        self::_needsMasterDB();
        $sth = self::$_db->prepare($query.';');
        if (!is_array($params)) {
            $params = array_slice(func_get_args(),1);
        }

        $sth->execute($params);
        return $sth->fetchAll(PDO::FETCH_ASSOC);
    }


    static public function execute($query, $params = []) {
        self::_needsMasterDB();
        $sth = self::$_db->prepare($query.';');
        if (!is_array($params)) {
            $params = array_slice(func_get_args(),1);
        }
        $sth->execute($params);
        return $sth->rowCount();

    }

    static public function insert($table, $values, $functions = []) {
        self::_needsMasterDB();
        list($query,$args) = self::_insert_prepare($table,$values,$functions);
        $sth = self::$_db->prepare($query.';');
        $sth->execute($args);
        return $sth->rowCount();
    }


    static public function update($table,$values,$whereclause,$functions="") {
        self::_needsMasterDB();
        $query = 'UPDATE "'. $table .'" SET ';
        $cnt=0;
        $where = "";
        $args = [];

        foreach ($values as $key => $val) {
            if ($cnt) {
                $query .=', ';
            }
            $query .= '"'. $key .'"=?';
            if (is_bool($val)) {
                $args[] = ($val) ? 'TRUE' : 'FALSE';
            }
            else {
                $args[] = $val;
            }
            $cnt++;
        }

        if ($functions!="") {
            foreach ($functions as $key => $val) {
                if ($cnt) {
                    $query .=', ';
                }
                $query .= '"'. $key .'"'. $val;
                $cnt++;
            }
        }

        if (empty($values)) {
            $query = 'SELECT * FROM '.$table;
        }

        if (is_array($whereclause)) {
            $cnt=0;
            foreach ($whereclause as $key => $val) {
                if ($cnt) {
                    $where .=' AND ';
                }
                $where .= '("'. $key .'"=?)';
                $args[] = $val;
                $cnt++;
            }
            $query .= " WHERE ".$where .";";
        }
        else {
            $query .= " WHERE ". $whereclause .";";
        }

        $sth = self::$_db->prepare($query.';');
        $sth->execute($args);
        return $sth->rowCount();
    }


    public static function set($table,$values,$wherelist,$functions = []) {
        $rowsAffected = self::update($table,$values,$wherelist,$functions);
        if ($rowsAffected == 0) {
            return self::insert($table,array_merge($values,$wherelist),$functions);
        }
        return $rowsAffcted;
    }


    public static function delete($table, $values, $extrarules="") {
        $query = 'DELETE FROM "'. $table .'" WHERE ';
        $cnt=0;
        $args = [];
        foreach ($values as $key => $val) {
            if ($cnt) {
                $query .= 'AND';
            }
            $query .= ' ("'. $key .'" = ?)';
            $args[] = $val;
            $cnt++;
        }

        if ($extrarules !== "") {
            $query .= ' AND '.$extrarules;
        }
        return self::execute($query,$args);
    }

    static private function _insert_prepare($table,$values,$functions = []) {
        $query = 'INSERT INTO "'. $table .'"(';
        $cnt=0;
        $valbuf = "";
        $args = [];
        foreach ($values as $key => $val) {
            if ($cnt) {
                $query .=',';
                $valbuf.=',';
            }
            $query .= '"'. $key .'"';
            $valbuf .= '?';

            if (is_bool($val)) {
                $args[] = ($val) ? 'TRUE' : 'FALSE';
            }
            elseif ($val===null) {
                $args[] = NULL;
            }
            else {
                $args[] = $val;
            }
            $cnt++;
        }

        foreach ($functions as $key => $val) {
            if ($cnt) {
                $query .=',';
                $valbuf .=',';
            }
            $query .= '"'. $key .'"';
            $valbuf .= $val;

            $cnt++;
        }

        $query .= ") VALUES (". $valbuf .");";

        return [$query, $args];
    }


    public static function begin() {
        self::_needsMasterDB();
        if (self::$_transaction_depth == 0) {
            self::$_db->beginTransaction();
            self::$_transaction_depth++;
        }
        elseif (self::$_transaction_failed) {
            throw new Exception("Trying to begin transaction inside of already stopped transaction!");
        }
        else {
            self::$_transaction_depth++;
        }
    }

    public static function commit() {
        if (self::$_transaction_depth>0) {
            if (self::$_transaction_failed) {
                // I'm not convinced that it's good idea,
                // but we need to be sure transaction won't go to database.
                self::rollback();
                throw new Exception("Transaction already stopped, couldn't be commited");
            }
            self::$_transaction_depth--;
            if (self::$_transaction_depth==0) {
                return self::$_db->commit();
            }
        }
        else {
            throw new Exception("To commit transaction it needs to be started first");
        }
    }

    public static function rollback() {
        self::$_transaction_failed = true;
        self::$_transaction_depth--;
        if (self::$_transaction_depth == 0) {
            self::$_db->rollback();
            self::$_transaction_failed = false;
        }
    }

    public static function inTransaction() {
        return (self::$_transaction_depth>0);
    }

    public static function transactionStateFailed() {
        return self::$_transaction_failed;
    }
}

?>