1
|
|
|
<?php |
2
|
|
|
defined('ROOT_PATH') || exit('Access denied'); |
3
|
|
|
/** |
4
|
|
|
* TNH Framework |
5
|
|
|
* |
6
|
|
|
* A simple PHP framework using HMVC architecture |
7
|
|
|
* |
8
|
|
|
* This content is released under the GNU GPL License (GPL) |
9
|
|
|
* |
10
|
|
|
* Copyright (C) 2017 Tony NGUEREZA |
11
|
|
|
* |
12
|
|
|
* This program is free software; you can redistribute it and/or |
13
|
|
|
* modify it under the terms of the GNU General Public License |
14
|
|
|
* as published by the Free Software Foundation; either version 3 |
15
|
|
|
* of the License, or (at your option) any later version. |
16
|
|
|
* |
17
|
|
|
* This program is distributed in the hope that it will be useful, |
18
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
19
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
20
|
|
|
* GNU General Public License for more details. |
21
|
|
|
* |
22
|
|
|
* You should have received a copy of the GNU General Public License |
23
|
|
|
* along with this program; if not, write to the Free Software |
24
|
|
|
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
25
|
|
|
*/ |
26
|
|
|
class Database{ |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* The PDO instance |
30
|
|
|
* @var object |
31
|
|
|
*/ |
32
|
|
|
private $pdo = null; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* The database name used for the application |
36
|
|
|
* @var string |
37
|
|
|
*/ |
38
|
|
|
private $databaseName = null; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* The number of rows returned by the last query |
42
|
|
|
* @var int |
43
|
|
|
*/ |
44
|
|
|
private $numRows = 0; |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* The last insert id for the primary key column that have auto increment or sequence |
48
|
|
|
* @var mixed |
49
|
|
|
*/ |
50
|
|
|
private $insertId = null; |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* The full SQL query statment after build for each command |
54
|
|
|
* @var string |
55
|
|
|
*/ |
56
|
|
|
private $query = null; |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* The error returned for the last query |
60
|
|
|
* @var string |
61
|
|
|
*/ |
62
|
|
|
private $error = null; |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* The result returned for the last query |
66
|
|
|
* @var mixed |
67
|
|
|
*/ |
68
|
|
|
private $result = array(); |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* The cache default time to live in second. 0 means no need to use the cache feature |
72
|
|
|
* @var int |
73
|
|
|
*/ |
74
|
|
|
private $cacheTtl = 0; |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* The cache current time to live. 0 means no need to use the cache feature |
78
|
|
|
* @var int |
79
|
|
|
*/ |
80
|
|
|
private $temporaryCacheTtl = 0; |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* The number of executed query for the current request |
84
|
|
|
* @var int |
85
|
|
|
*/ |
86
|
|
|
private $queryCount = 0; |
87
|
|
|
|
88
|
|
|
/** |
89
|
|
|
* The default data to be used in the statments query INSERT, UPDATE |
90
|
|
|
* @var array |
91
|
|
|
*/ |
92
|
|
|
private $data = array(); |
93
|
|
|
|
94
|
|
|
/** |
95
|
|
|
* The database configuration |
96
|
|
|
* @var array |
97
|
|
|
*/ |
98
|
|
|
private $config = array(); |
99
|
|
|
|
100
|
|
|
/** |
101
|
|
|
* The logger instance |
102
|
|
|
* @var object |
103
|
|
|
*/ |
104
|
|
|
private $logger = null; |
105
|
|
|
|
106
|
|
|
/** |
107
|
|
|
* The cache instance |
108
|
|
|
* @var object |
109
|
|
|
*/ |
110
|
|
|
private $cacheInstance = null; |
111
|
|
|
|
112
|
|
|
/** |
113
|
|
|
* The benchmark instance |
114
|
|
|
* @var object |
115
|
|
|
*/ |
116
|
|
|
private $benchmarkInstance = null; |
117
|
|
|
|
118
|
|
|
/** |
119
|
|
|
* The DatabaseQueryBuilder instance |
120
|
|
|
* @var object |
121
|
|
|
*/ |
122
|
|
|
private $queryBuilder = null; |
123
|
|
|
|
124
|
|
|
|
125
|
|
|
/** |
126
|
|
|
* Construct new database |
127
|
|
|
* @param array $overwriteConfig the config to overwrite with the config set in database.php |
128
|
|
|
*/ |
129
|
|
|
public function __construct($overwriteConfig = array()){ |
130
|
|
|
//Set Log instance to use |
131
|
|
|
$this->setLoggerFromParamOrCreateNewInstance(null); |
132
|
|
|
|
133
|
|
|
//Set DatabaseQueryBuilder instance to use |
134
|
|
|
$this->setQueryBuilderFromParamOrCreateNewInstance(null); |
135
|
|
|
|
136
|
|
|
//Set database configuration |
137
|
|
|
$this->setDatabaseConfiguration($overwriteConfig); |
138
|
|
|
|
139
|
|
|
//cache time to live |
140
|
|
|
$this->temporaryCacheTtl = $this->cacheTtl; |
141
|
|
|
} |
142
|
|
|
|
143
|
|
|
/** |
144
|
|
|
* This is used to connect to database |
145
|
|
|
* @return bool |
146
|
|
|
*/ |
147
|
|
|
public function connect(){ |
148
|
|
|
$config = $this->getDatabaseConfiguration(); |
149
|
|
|
if (! empty($config)){ |
150
|
|
|
try{ |
151
|
|
|
$this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']); |
152
|
|
|
$this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'"); |
153
|
|
|
$this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'"); |
154
|
|
|
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); |
155
|
|
|
return true; |
156
|
|
|
} |
157
|
|
|
catch (PDOException $e){ |
158
|
|
|
$this->logger->fatal($e->getMessage()); |
159
|
|
|
show_error('Cannot connect to Database.'); |
160
|
|
|
return false; |
161
|
|
|
} |
162
|
|
|
} |
163
|
|
|
else{ |
164
|
|
|
show_error('Database configuration is not set.'); |
165
|
|
|
return false; |
166
|
|
|
} |
167
|
|
|
} |
168
|
|
|
|
169
|
|
|
|
170
|
|
|
/** |
171
|
|
|
* Return the number of rows returned by the current query |
172
|
|
|
* @return int |
173
|
|
|
*/ |
174
|
|
|
public function numRows(){ |
175
|
|
|
return $this->numRows; |
176
|
|
|
} |
177
|
|
|
|
178
|
|
|
/** |
179
|
|
|
* Return the last insert id value |
180
|
|
|
* @return mixed |
181
|
|
|
*/ |
182
|
|
|
public function insertId(){ |
183
|
|
|
return $this->insertId; |
184
|
|
|
} |
185
|
|
|
|
186
|
|
|
/** |
187
|
|
|
* Show an error got from the current query (SQL command synthax error, database driver returned error, etc.) |
188
|
|
|
*/ |
189
|
|
|
public function error(){ |
190
|
|
|
if ($this->error){ |
191
|
|
|
show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error'); |
192
|
|
|
} |
193
|
|
|
} |
194
|
|
|
|
195
|
|
|
/** |
196
|
|
|
* Get the result of one record rows returned by the current query |
197
|
|
|
* @param boolean $returnSQLQueryOrResultType if is boolean and true will return the SQL query string. |
198
|
|
|
* If is string will determine the result type "array" or "object" |
199
|
|
|
* @return mixed the query SQL string or the record result |
200
|
|
|
*/ |
201
|
|
|
public function get($returnSQLQueryOrResultType = false){ |
202
|
|
|
$this->getQueryBuilder()->limit(1); |
203
|
|
|
$query = $this->getAll(true); |
204
|
|
|
if ($returnSQLQueryOrResultType === true){ |
205
|
|
|
return $query; |
206
|
|
|
} |
207
|
|
|
else{ |
208
|
|
|
return $this->query($query, false, $returnSQLQueryOrResultType == 'array'); |
209
|
|
|
} |
210
|
|
|
} |
211
|
|
|
|
212
|
|
|
/** |
213
|
|
|
* Get the result of record rows list returned by the current query |
214
|
|
|
* @param boolean|string $returnSQLQueryOrResultType if is boolean and true will return the SQL query string. |
215
|
|
|
* If is string will determine the result type "array" or "object" |
216
|
|
|
* @return mixed the query SQL string or the record result |
217
|
|
|
*/ |
218
|
|
|
public function getAll($returnSQLQueryOrResultType = false){ |
219
|
|
|
$query = $this->getQueryBuilder()->getQuery(); |
220
|
|
|
if ($returnSQLQueryOrResultType === true){ |
221
|
|
|
return $query; |
222
|
|
|
} |
223
|
|
|
return $this->query($query, true, $returnSQLQueryOrResultType == 'array'); |
224
|
|
|
} |
225
|
|
|
|
226
|
|
|
/** |
227
|
|
|
* Insert new record in the database |
228
|
|
|
* @param array $data the record data if is empty will use the $this->data array. |
229
|
|
|
* @param boolean $escape whether to escape or not the values |
230
|
|
|
* @return mixed the insert id of the new record or null |
231
|
|
|
*/ |
232
|
|
|
public function insert($data = array(), $escape = true){ |
233
|
|
|
if (empty($data) && $this->getData()){ |
234
|
|
|
//as when using $this->setData() may be the data already escaped |
235
|
|
|
$escape = false; |
236
|
|
|
$data = $this->getData(); |
237
|
|
|
} |
238
|
|
|
$query = $this->getQueryBuilder()->insert($data, $escape)->getQuery(); |
239
|
|
|
$result = $this->query($query); |
240
|
|
|
if ($result){ |
241
|
|
|
$this->insertId = $this->pdo->lastInsertId(); |
242
|
|
|
//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned |
243
|
|
|
return ! $this->insertId() ? true : $this->insertId(); |
244
|
|
|
} |
245
|
|
|
return false; |
246
|
|
|
} |
247
|
|
|
|
248
|
|
|
/** |
249
|
|
|
* Update record in the database |
250
|
|
|
* @param array $data the record data if is empty will use the $this->data array. |
251
|
|
|
* @param boolean $escape whether to escape or not the values |
252
|
|
|
* @return mixed the update status |
253
|
|
|
*/ |
254
|
|
|
public function update($data = array(), $escape = true){ |
255
|
|
|
if (empty($data) && $this->getData()){ |
256
|
|
|
//as when using $this->setData() may be the data already escaped |
257
|
|
|
$escape = false; |
258
|
|
|
$data = $this->getData(); |
259
|
|
|
} |
260
|
|
|
$query = $this->getQueryBuilder()->update($data, $escape)->getQuery(); |
261
|
|
|
return $this->query($query); |
262
|
|
|
} |
263
|
|
|
|
264
|
|
|
/** |
265
|
|
|
* Delete the record in database |
266
|
|
|
* @return mixed the delete status |
267
|
|
|
*/ |
268
|
|
|
public function delete(){ |
269
|
|
|
$query = $this->getQueryBuilder()->delete()->getQuery(); |
270
|
|
|
return $this->query($query); |
271
|
|
|
} |
272
|
|
|
|
273
|
|
|
/** |
274
|
|
|
* Set database cache time to live |
275
|
|
|
* @param integer $ttl the cache time to live in second |
276
|
|
|
* @return object the current Database instance |
277
|
|
|
*/ |
278
|
|
|
public function setCache($ttl = 0){ |
279
|
|
|
if ($ttl > 0){ |
280
|
|
|
$this->cacheTtl = $ttl; |
281
|
|
|
$this->temporaryCacheTtl = $ttl; |
282
|
|
|
} |
283
|
|
|
return $this; |
284
|
|
|
} |
285
|
|
|
|
286
|
|
|
/** |
287
|
|
|
* Enabled cache temporary for the current query not globally |
288
|
|
|
* @param integer $ttl the cache time to live in second |
289
|
|
|
* @return object the current Database instance |
290
|
|
|
*/ |
291
|
|
|
public function cached($ttl = 0){ |
292
|
|
|
if ($ttl > 0){ |
293
|
|
|
$this->temporaryCacheTtl = $ttl; |
294
|
|
|
} |
295
|
|
|
return $this; |
296
|
|
|
} |
297
|
|
|
|
298
|
|
|
/** |
299
|
|
|
* Escape the data before execute query useful for security. |
300
|
|
|
* @param mixed $data the data to be escaped |
301
|
|
|
* @param boolean $escaped whether we can do escape of not |
302
|
|
|
* @return mixed the data after escaped or the same data if not |
303
|
|
|
*/ |
304
|
|
|
public function escape($data, $escaped = true){ |
305
|
|
|
return $escaped ? |
306
|
|
|
$this->getPdo()->quote(trim($data)) |
307
|
|
|
: $data; |
308
|
|
|
} |
309
|
|
|
|
310
|
|
|
/** |
311
|
|
|
* Return the number query executed count for the current request |
312
|
|
|
* @return int |
313
|
|
|
*/ |
314
|
|
|
public function queryCount(){ |
315
|
|
|
return $this->queryCount; |
316
|
|
|
} |
317
|
|
|
|
318
|
|
|
/** |
319
|
|
|
* Return the current query SQL string |
320
|
|
|
* @return string |
321
|
|
|
*/ |
322
|
|
|
public function getQuery(){ |
323
|
|
|
return $this->query; |
324
|
|
|
} |
325
|
|
|
|
326
|
|
|
/** |
327
|
|
|
* Return the application database name |
328
|
|
|
* @return string |
329
|
|
|
*/ |
330
|
|
|
public function getDatabaseName(){ |
331
|
|
|
return $this->databaseName; |
332
|
|
|
} |
333
|
|
|
|
334
|
|
|
/** |
335
|
|
|
* Return the PDO instance |
336
|
|
|
* @return object |
337
|
|
|
*/ |
338
|
|
|
public function getPdo(){ |
339
|
|
|
return $this->pdo; |
340
|
|
|
} |
341
|
|
|
|
342
|
|
|
/** |
343
|
|
|
* Set the PDO instance |
344
|
|
|
* @param object $pdo the pdo object |
345
|
|
|
* @return object Database |
346
|
|
|
*/ |
347
|
|
|
public function setPdo(PDO $pdo){ |
348
|
|
|
$this->pdo = $pdo; |
349
|
|
|
return $this; |
350
|
|
|
} |
351
|
|
|
|
352
|
|
|
|
353
|
|
|
/** |
354
|
|
|
* Return the Log instance |
355
|
|
|
* @return Log |
356
|
|
|
*/ |
357
|
|
|
public function getLogger(){ |
358
|
|
|
return $this->logger; |
359
|
|
|
} |
360
|
|
|
|
361
|
|
|
/** |
362
|
|
|
* Set the log instance |
363
|
|
|
* @param Log $logger the log object |
364
|
|
|
* @return object Database |
365
|
|
|
*/ |
366
|
|
|
public function setLogger($logger){ |
367
|
|
|
$this->logger = $logger; |
368
|
|
|
return $this; |
369
|
|
|
} |
370
|
|
|
|
371
|
|
|
/** |
372
|
|
|
* Return the cache instance |
373
|
|
|
* @return CacheInterface |
374
|
|
|
*/ |
375
|
|
|
public function getCacheInstance(){ |
376
|
|
|
return $this->cacheInstance; |
377
|
|
|
} |
378
|
|
|
|
379
|
|
|
/** |
380
|
|
|
* Set the cache instance |
381
|
|
|
* @param CacheInterface $cache the cache object |
382
|
|
|
* @return object Database |
383
|
|
|
*/ |
384
|
|
|
public function setCacheInstance($cache){ |
385
|
|
|
$this->cacheInstance = $cache; |
386
|
|
|
return $this; |
387
|
|
|
} |
388
|
|
|
|
389
|
|
|
/** |
390
|
|
|
* Return the benchmark instance |
391
|
|
|
* @return Benchmark |
392
|
|
|
*/ |
393
|
|
|
public function getBenchmark(){ |
394
|
|
|
return $this->benchmarkInstance; |
395
|
|
|
} |
396
|
|
|
|
397
|
|
|
/** |
398
|
|
|
* Set the benchmark instance |
399
|
|
|
* @param Benchmark $benchmark the benchmark object |
400
|
|
|
* @return object Database |
401
|
|
|
*/ |
402
|
|
|
public function setBenchmark($benchmark){ |
403
|
|
|
$this->benchmarkInstance = $benchmark; |
404
|
|
|
return $this; |
405
|
|
|
} |
406
|
|
|
|
407
|
|
|
|
408
|
|
|
/** |
409
|
|
|
* Return the DatabaseQueryBuilder instance |
410
|
|
|
* @return object DatabaseQueryBuilder |
411
|
|
|
*/ |
412
|
|
|
public function getQueryBuilder(){ |
413
|
|
|
return $this->queryBuilder; |
414
|
|
|
} |
415
|
|
|
|
416
|
|
|
/** |
417
|
|
|
* Set the DatabaseQueryBuilder instance |
418
|
|
|
* @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object |
419
|
|
|
*/ |
420
|
|
|
public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){ |
421
|
|
|
$this->queryBuilder = $queryBuilder; |
422
|
|
|
return $this; |
423
|
|
|
} |
424
|
|
|
|
425
|
|
|
/** |
426
|
|
|
* Return the data to be used for insert, update, etc. |
427
|
|
|
* @return array |
428
|
|
|
*/ |
429
|
|
|
public function getData(){ |
430
|
|
|
return $this->data; |
431
|
|
|
} |
432
|
|
|
|
433
|
|
|
/** |
434
|
|
|
* Set the data to be used for insert, update, etc. |
435
|
|
|
* @param string|array $key the data key identified |
436
|
|
|
* @param mixed $value the data value |
437
|
|
|
* @param boolean $escape whether to escape or not the $value |
438
|
|
|
* @return object the current Database instance |
439
|
|
|
*/ |
440
|
|
|
public function setData($key, $value = null, $escape = true){ |
441
|
|
|
if(is_array($key)){ |
442
|
|
|
foreach($key as $k => $v){ |
443
|
|
|
$this->setData($k, $v, $escape); |
444
|
|
|
} |
445
|
|
|
} else { |
446
|
|
|
$this->data[$key] = $this->escape($value, $escape); |
447
|
|
|
} |
448
|
|
|
return $this; |
449
|
|
|
} |
450
|
|
|
|
451
|
|
|
/** |
452
|
|
|
* Execute an SQL query |
453
|
|
|
* @param string $query the query SQL string |
454
|
|
|
* @param boolean|array $all if boolean this indicate whether to return all record or not, if array |
455
|
|
|
* will |
456
|
|
|
* @param boolean $array return the result as array |
457
|
|
|
* @return mixed the query result |
458
|
|
|
*/ |
459
|
|
|
public function query($query, $all = true, $array = false){ |
460
|
|
|
$this->reset(); |
461
|
|
|
$query = $this->getPreparedQuery($query, $all); |
462
|
|
|
$this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query)); |
463
|
|
|
|
464
|
|
|
$isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false; |
465
|
|
|
|
466
|
|
|
$this->logger->info( |
467
|
|
|
'Execute SQL query ['.$this->query.'], return type: ' |
468
|
|
|
. ($array?'ARRAY':'OBJECT') .', return as list: ' |
469
|
|
|
. (is_bool($all) && $all ? 'YES':'NO') |
470
|
|
|
); |
471
|
|
|
//cache expire time |
472
|
|
|
$cacheExpire = $this->temporaryCacheTtl; |
473
|
|
|
|
474
|
|
|
//return to the initial cache time |
475
|
|
|
$this->temporaryCacheTtl = $this->cacheTtl; |
476
|
|
|
|
477
|
|
|
//config for cache |
478
|
|
|
$cacheEnable = get_config('cache_enable'); |
479
|
|
|
|
480
|
|
|
//the database cache content |
481
|
|
|
$cacheContent = null; |
482
|
|
|
|
483
|
|
|
//if can use cache feature for this query |
484
|
|
|
$dbCacheStatus = $cacheEnable && $cacheExpire > 0; |
485
|
|
|
|
486
|
|
|
if ($dbCacheStatus && $isSqlSELECTQuery){ |
487
|
|
|
$this->logger->info('The cache is enabled for this query, try to get result from cache'); |
488
|
|
|
$cacheContent = $this->getCacheContentForQuery($query, $all, $array); |
489
|
|
|
} |
490
|
|
|
|
491
|
|
|
if ( !$cacheContent){ |
492
|
|
|
$sqlQuery = $this->runSqlQuery($query, $all, $array); |
493
|
|
|
if (is_object($sqlQuery)){ |
494
|
|
|
if ($isSqlSELECTQuery){ |
495
|
|
|
$this->setQueryResultForSelect($sqlQuery, $all, $array); |
496
|
|
|
$this->setCacheContentForQuery( |
497
|
|
|
$this->query, |
498
|
|
|
$this->getCacheBenchmarkKeyForQuery($this->query, $all, $array), |
499
|
|
|
$this->result, |
500
|
|
|
$dbCacheStatus && $isSqlSELECTQuery, |
501
|
|
|
$cacheExpire |
502
|
|
|
); |
503
|
|
|
if (! $this->result){ |
504
|
|
|
$this->logger->info('No result where found for the query [' . $query . ']'); |
505
|
|
|
} |
506
|
|
|
} else { |
507
|
|
|
$this->setQueryResultForNonSelect($sqlQuery); |
508
|
|
|
} |
509
|
|
|
} |
510
|
|
|
} else if ($isSqlSELECTQuery){ |
511
|
|
|
$this->logger->info('The result for query [' .$this->query. '] already cached use it'); |
512
|
|
|
$this->result = $cacheContent; |
513
|
|
|
$this->numRows = count($this->result); |
514
|
|
|
} |
515
|
|
|
return $this->result; |
516
|
|
|
} |
517
|
|
|
|
518
|
|
|
/** |
519
|
|
|
* Run the database SQL query and return the PDOStatment object |
520
|
|
|
* @see Database::query |
521
|
|
|
* |
522
|
|
|
* @return object|void |
523
|
|
|
*/ |
524
|
|
|
public function runSqlQuery($query, $all, $array){ |
525
|
|
|
//for database query execution time |
526
|
|
|
$benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array); |
527
|
|
|
$benchmarkInstance = $this->getBenchmark(); |
528
|
|
|
if (! is_object($benchmarkInstance)){ |
529
|
|
|
$obj = & get_instance(); |
530
|
|
|
$benchmarkInstance = $obj->benchmark; |
531
|
|
|
$this->setBenchmark($benchmarkInstance); |
532
|
|
|
} |
533
|
|
|
|
534
|
|
|
$benchmarkInstance->mark('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')'); |
535
|
|
|
//Now execute the query |
536
|
|
|
$sqlQuery = $this->pdo->query($query); |
537
|
|
|
|
538
|
|
|
//get response time for this query |
539
|
|
|
$responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')'); |
540
|
|
|
//TODO use the configuration value for the high response time currently is 1 second |
541
|
|
|
if ($responseTime >= 1 ){ |
542
|
|
|
$this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.'); |
543
|
|
|
} |
544
|
|
|
//count the number of query execution to server |
545
|
|
|
$this->queryCount++; |
546
|
|
|
|
547
|
|
|
if ($sqlQuery !== false){ |
548
|
|
|
return $sqlQuery; |
549
|
|
|
} |
550
|
|
|
$this->setQueryError(); |
551
|
|
|
} |
552
|
|
|
|
553
|
|
|
|
554
|
|
|
/** |
555
|
|
|
* Return the database configuration |
556
|
|
|
* @return array |
557
|
|
|
*/ |
558
|
|
|
public function getDatabaseConfiguration(){ |
559
|
|
|
return $this->config; |
560
|
|
|
} |
561
|
|
|
|
562
|
|
|
/** |
563
|
|
|
* Setting the database configuration using the configuration file and additional configuration from param |
564
|
|
|
* @param array $overwriteConfig the additional configuration to overwrite with the existing one |
565
|
|
|
* @param boolean $useConfigFile whether to use database configuration file |
566
|
|
|
* @return object Database |
567
|
|
|
*/ |
568
|
|
|
public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){ |
569
|
|
|
$db = array(); |
570
|
|
|
if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){ |
571
|
|
|
//here don't use require_once because somewhere user can create database instance directly |
572
|
|
|
require CONFIG_PATH . 'database.php'; |
573
|
|
|
} |
574
|
|
|
|
575
|
|
|
//merge with the parameter |
576
|
|
|
$db = array_merge($db, $overwriteConfig); |
577
|
|
|
|
578
|
|
|
//default configuration |
579
|
|
|
$config = array( |
580
|
|
|
'driver' => 'mysql', |
581
|
|
|
'username' => 'root', |
582
|
|
|
'password' => '', |
583
|
|
|
'database' => '', |
584
|
|
|
'hostname' => 'localhost', |
585
|
|
|
'charset' => 'utf8', |
586
|
|
|
'collation' => 'utf8_general_ci', |
587
|
|
|
'prefix' => '', |
588
|
|
|
'port' => '' |
589
|
|
|
); |
590
|
|
|
|
591
|
|
|
$config = array_merge($config, $db); |
592
|
|
|
//determine the port using the hostname like localhost:3307 |
593
|
|
|
//hostname will be "localhost", and port "3307" |
594
|
|
|
$p = explode(':', $config['hostname']); |
595
|
|
|
if (count($p) >= 2){ |
596
|
|
|
$config['hostname'] = $p[0]; |
597
|
|
|
$config['port'] = $p[1]; |
598
|
|
|
} |
599
|
|
|
|
600
|
|
|
$this->databaseName = $config['database']; |
601
|
|
|
$this->config = $config; |
602
|
|
|
$this->logger->info( |
603
|
|
|
'The database configuration are listed below: ' |
604
|
|
|
. stringfy_vars(array_merge( |
605
|
|
|
$this->config, |
606
|
|
|
array('password' => string_hidden($this->config['password'])) |
607
|
|
|
)) |
608
|
|
|
); |
609
|
|
|
|
610
|
|
|
//Now connect to the database |
611
|
|
|
$this->connect(); |
612
|
|
|
|
613
|
|
|
//update queryBuilder with some properties needed |
614
|
|
|
if(is_object($this->getQueryBuilder())){ |
615
|
|
|
$this->getQueryBuilder()->setDriver($config['driver']); |
616
|
|
|
$this->getQueryBuilder()->setPrefix($config['prefix']); |
617
|
|
|
$this->getQueryBuilder()->setPdo($this->getPdo()); |
618
|
|
|
} |
619
|
|
|
return $this; |
620
|
|
|
} |
621
|
|
|
|
622
|
|
|
/** |
623
|
|
|
* Set the result for SELECT query using PDOStatment |
624
|
|
|
* @see Database::query |
625
|
|
|
*/ |
626
|
|
|
protected function setQueryResultForSelect($pdoStatment, $all, $array){ |
627
|
|
|
//if need return all result like list of record |
628
|
|
|
if (is_bool($all) && $all){ |
629
|
|
|
$this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC); |
630
|
|
|
} |
631
|
|
|
else{ |
632
|
|
|
$this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC); |
633
|
|
|
} |
634
|
|
|
//Sqlite and pgsql always return 0 when using rowCount() |
635
|
|
|
if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){ |
636
|
|
|
$this->numRows = count($this->result); |
637
|
|
|
} |
638
|
|
|
else{ |
639
|
|
|
$this->numRows = $pdoStatment->rowCount(); |
640
|
|
|
} |
641
|
|
|
} |
642
|
|
|
|
643
|
|
|
/** |
644
|
|
|
* Set the result for other command than SELECT query using PDOStatment |
645
|
|
|
* @see Database::query |
646
|
|
|
*/ |
647
|
|
|
protected function setQueryResultForNonSelect($pdoStatment){ |
648
|
|
|
//Sqlite and pgsql always return 0 when using rowCount() |
649
|
|
|
if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){ |
650
|
|
|
$this->result = true; //to test the result for the query like UPDATE, INSERT, DELETE |
651
|
|
|
$this->numRows = 1; //TODO use the correct method to get the exact affected row |
652
|
|
|
} |
653
|
|
|
else{ |
654
|
|
|
$this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE |
655
|
|
|
$this->numRows = $pdoStatment->rowCount(); |
656
|
|
|
} |
657
|
|
|
} |
658
|
|
|
|
659
|
|
|
|
660
|
|
|
|
661
|
|
|
/** |
662
|
|
|
* This method is used to get the PDO DSN string using the configured driver |
663
|
|
|
* @return string the DSN string |
664
|
|
|
*/ |
665
|
|
|
protected function getDsnFromDriver(){ |
666
|
|
|
$config = $this->getDatabaseConfiguration(); |
667
|
|
|
if (! empty($config)){ |
668
|
|
|
$driver = $config['driver']; |
669
|
|
|
$driverDsnMap = array( |
670
|
|
|
'mysql' => 'mysql:host=' . $config['hostname'] . ';' |
671
|
|
|
. (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') |
672
|
|
|
. 'dbname=' . $config['database'], |
673
|
|
|
'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' |
674
|
|
|
. (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') |
675
|
|
|
. 'dbname=' . $config['database'], |
676
|
|
|
'sqlite' => 'sqlite:' . $config['database'], |
677
|
|
|
'oracle' => 'oci:dbname=' . $config['hostname'] |
678
|
|
|
. (($config['port']) != '' ? ':' . $config['port'] : '') |
679
|
|
|
. '/' . $config['database'] |
680
|
|
|
); |
681
|
|
|
return isset($driverDsnMap[$driver]) ? $driverDsnMap[$driver] : ''; |
682
|
|
|
} |
683
|
|
|
return null; |
684
|
|
|
} |
685
|
|
|
|
686
|
|
|
/** |
687
|
|
|
* Transform the prepared query like (?, ?, ?) into string format |
688
|
|
|
* @see Database::query |
689
|
|
|
* |
690
|
|
|
* @return string |
691
|
|
|
*/ |
692
|
|
|
protected function getPreparedQuery($query, $data){ |
693
|
|
|
if (is_array($data)){ |
694
|
|
|
$x = explode('?', $query); |
695
|
|
|
$q = ''; |
696
|
|
|
foreach($x as $k => $v){ |
697
|
|
|
if (! empty($v)){ |
698
|
|
|
$q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : ''); |
699
|
|
|
} |
700
|
|
|
} |
701
|
|
|
return $q; |
702
|
|
|
} |
703
|
|
|
return $query; |
704
|
|
|
} |
705
|
|
|
|
706
|
|
|
/** |
707
|
|
|
* Get the cache content for this query |
708
|
|
|
* @see Database::query |
709
|
|
|
* |
710
|
|
|
* @return mixed |
711
|
|
|
*/ |
712
|
|
|
protected function getCacheContentForQuery($query, $all, $array){ |
713
|
|
|
$cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array); |
714
|
|
|
if (! is_object($this->getCacheInstance())){ |
715
|
|
|
//can not call method with reference in argument |
716
|
|
|
//like $this->setCacheInstance(& get_instance()->cache); |
717
|
|
|
//use temporary variable |
718
|
|
|
$instance = & get_instance()->cache; |
719
|
|
|
$this->setCacheInstance($instance); |
720
|
|
|
} |
721
|
|
|
return $this->getCacheInstance()->get($cacheKey); |
722
|
|
|
} |
723
|
|
|
|
724
|
|
|
/** |
725
|
|
|
* Save the result of query into cache |
726
|
|
|
* @param string $query the SQL query |
727
|
|
|
* @param string $key the cache key |
728
|
|
|
* @param mixed $result the query result to save |
729
|
|
|
* @param boolean $status whether can save the query result into cache |
730
|
|
|
* @param int $expire the cache TTL |
731
|
|
|
*/ |
732
|
|
|
protected function setCacheContentForQuery($query, $key, $result, $status, $expire){ |
733
|
|
|
if ($status){ |
734
|
|
|
$this->logger->info('Save the result for query [' .$query. '] into cache for future use'); |
735
|
|
|
if (! is_object($this->getCacheInstance())){ |
736
|
|
|
//can not call method with reference in argument |
737
|
|
|
//like $this->setCacheInstance(& get_instance()->cache); |
738
|
|
|
//use temporary variable |
739
|
|
|
$instance = & get_instance()->cache; |
740
|
|
|
$this->setCacheInstance($instance); |
741
|
|
|
} |
742
|
|
|
$this->getCacheInstance()->set($key, $result, $expire); |
743
|
|
|
} |
744
|
|
|
} |
745
|
|
|
|
746
|
|
|
|
747
|
|
|
/** |
748
|
|
|
* Set error for database query execution |
749
|
|
|
*/ |
750
|
|
|
protected function setQueryError(){ |
751
|
|
|
$error = $this->pdo->errorInfo(); |
752
|
|
|
$this->error = isset($error[2]) ? $error[2] : ''; |
753
|
|
|
$this->logger->error('The database query execution got error: ' . stringfy_vars($error)); |
754
|
|
|
//show error message |
755
|
|
|
$this->error(); |
756
|
|
|
} |
757
|
|
|
|
758
|
|
|
/** |
759
|
|
|
* Return the cache key for the given query |
760
|
|
|
* @see Database::query |
761
|
|
|
* |
762
|
|
|
* @return string |
763
|
|
|
*/ |
764
|
|
|
protected function getCacheBenchmarkKeyForQuery($query, $all, $array){ |
765
|
|
|
if (is_array($all)){ |
766
|
|
|
$all = 'array'; |
767
|
|
|
} |
768
|
|
|
return md5($query . $all . $array); |
769
|
|
|
} |
770
|
|
|
|
771
|
|
|
/** |
772
|
|
|
* Set the Log instance using argument or create new instance |
773
|
|
|
* @param object $logger the Log instance if not null |
774
|
|
|
*/ |
775
|
|
|
protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){ |
776
|
|
|
if ($logger !== null){ |
777
|
|
|
$this->setLogger($logger); |
778
|
|
|
} |
779
|
|
|
else{ |
780
|
|
|
$this->logger =& class_loader('Log', 'classes'); |
781
|
|
|
$this->logger->setLogger('Library::Database'); |
782
|
|
|
} |
783
|
|
|
} |
784
|
|
|
|
785
|
|
|
/** |
786
|
|
|
* Set the DatabaseQueryBuilder instance using argument or create new instance |
787
|
|
|
* @param object $queryBuilder the DatabaseQueryBuilder instance if not null |
788
|
|
|
*/ |
789
|
|
|
protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){ |
790
|
|
|
if ($queryBuilder !== null){ |
791
|
|
|
$this->setQueryBuilder($queryBuilder); |
792
|
|
|
} |
793
|
|
|
else{ |
794
|
|
|
$this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes'); |
795
|
|
|
} |
796
|
|
|
} |
797
|
|
|
|
798
|
|
|
/** |
799
|
|
|
* Reset the database class attributs to the initail values before each query. |
800
|
|
|
*/ |
801
|
|
|
private function reset(){ |
802
|
|
|
//query builder reset |
803
|
|
|
$this->getQueryBuilder()->reset(); |
804
|
|
|
$this->numRows = 0; |
805
|
|
|
$this->insertId = null; |
806
|
|
|
$this->query = null; |
807
|
|
|
$this->error = null; |
808
|
|
|
$this->result = array(); |
809
|
|
|
$this->data = array(); |
810
|
|
|
} |
811
|
|
|
|
812
|
|
|
/** |
813
|
|
|
* The class destructor |
814
|
|
|
*/ |
815
|
|
|
public function __destruct(){ |
816
|
|
|
$this->pdo = null; |
817
|
|
|
} |
818
|
|
|
|
819
|
|
|
} |
820
|
|
|
|