Passed
Push — 1.0.0-dev ( ead601...e21083 )
by nguereza
04:39
created

Database::in()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 9
c 1
b 1
f 0
nc 5
nop 5
dl 0
loc 12
rs 9.9666

1 Method

Rating   Name   Duplication   Size   Complexity  
A Database::getDatabaseConfiguration() 0 2 1
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
              if (! $this->result){
509
                $this->setQueryError();
510
              }
511
          }
512
        }
513
      } else if ($isSqlSELECTQuery){
514
          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
515
          $this->result = $cacheContent;
516
          $this->numRows = count($this->result);
517
      }
518
      return $this->result;
519
    }
520
	
521
	/**
522
     * Run the database SQL query and return the PDOStatment object
523
     * @see Database::query
524
     * 
525
     * @return object|void
526
     */
527
    public function runSqlQuery($query, $all, $array){
528
       //for database query execution time
529
        $benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
530
        $benchmarkInstance = $this->getBenchmark();
531
        if (! is_object($benchmarkInstance)){
532
          $obj = & get_instance();
533
          $benchmarkInstance = $obj->benchmark; 
534
          $this->setBenchmark($benchmarkInstance);
535
        }
536
        
537
        $benchmarkInstance->mark('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')');
538
        //Now execute the query
539
        $sqlQuery = $this->pdo->query($query);
540
        
541
        //get response time for this query
542
        $responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
543
		    //TODO use the configuration value for the high response time currently is 1 second
544
        if ($responseTime >= 1 ){
545
            $this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
546
        }
547
		    //count the number of query execution to server
548
        $this->queryCount++;
549
		
550
        if ($sqlQuery !== false){
551
          return $sqlQuery;
552
        }
553
        $this->setQueryError();
554
    }
555
	
556
	
557
	 /**
558
	 * Return the database configuration
559
	 * @return array
560
	 */
561
	public  function getDatabaseConfiguration(){
562
	  return $this->config;
563
	}
564
565
   /**
566
    * Setting the database configuration using the configuration file and additional configuration from param
567
    * @param array $overwriteConfig the additional configuration to overwrite with the existing one
568
    * @param boolean $useConfigFile whether to use database configuration file
569
	  * @return object Database
570
    */
571
    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
572
        $db = array();
573
        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
574
            //here don't use require_once because somewhere user can create database instance directly
575
            require CONFIG_PATH . 'database.php';
576
        }
577
          
578
        if (! empty($overwriteConfig)){
579
          $db = array_merge($db, $overwriteConfig);
580
        }
581
        $config = array(
582
          'driver' => 'mysql',
583
          'username' => 'root',
584
          'password' => '',
585
          'database' => '',
586
          'hostname' => 'localhost',
587
          'charset' => 'utf8',
588
          'collation' => 'utf8_general_ci',
589
          'prefix' => '',
590
          'port' => ''
591
        );
592
		
593
		$config = array_merge($config, $db);
594
		if (strstr($config['hostname'], ':')){
595
			$p = explode(':', $config['hostname']);
596
			if (count($p) >= 2){
597
			  $config['hostname'] = $p[0];
598
			  $config['port'] = $p[1];
599
			}
600
		 }
601
		 $this->databaseName = $config['database'];
602
		 $this->config = $config;
603
		 $this->logger->info(
604
								'The database configuration are listed below: ' 
605
								. stringfy_vars(array_merge(
606
															$this->config, 
607
															array('password' => string_hidden($this->config['password']))
608
												))
609
							);
610
	  
611
		 //Now connect to the database
612
		 $this->connect();
613
		 
614
		 //update queryBuilder with some properties needed
615
		 if(is_object($this->getQueryBuilder())){
616
			  $this->getQueryBuilder()->setDriver($config['driver']);
617
			  $this->getQueryBuilder()->setPrefix($config['prefix']);
618
			  $this->getQueryBuilder()->setPdo($this->getPdo());
619
		 }
620
		 return $this;
621
  }
622
	
623
   /**
624
   * Set the result for SELECT query using PDOStatment
625
   * @see Database::query
626
   */
627
    protected function setQueryResultForSelect($pdoStatment, $all, $array){
628
      //if need return all result like list of record
629
      if (is_bool($all) && $all){
630
          $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
631
      }
632
      else{
633
          $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
634
      }
635
      //Sqlite and pgsql always return 0 when using rowCount()
636
      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
637
        $this->numRows = count($this->result);  
638
      }
639
      else{
640
        $this->numRows = $pdoStatment->rowCount(); 
641
      }
642
    }
643
644
    /**
645
     * Set the result for other command than SELECT query using PDOStatment
646
     * @see Database::query
647
     */
648
    protected function setQueryResultForNonSelect($pdoStatment){
649
      //Sqlite and pgsql always return 0 when using rowCount()
650
      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
651
        $this->result = true; //to test the result for the query like UPDATE, INSERT, DELETE
652
        $this->numRows = 1; //TODO use the correct method to get the exact affected row
653
      }
654
      else{
655
          $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
656
          $this->numRows = $pdoStatment->rowCount(); 
657
      }
658
    }
659
660
	
661
662
    /**
663
     * This method is used to get the PDO DSN string using the configured driver
664
     * @return string the DSN string
665
     */
666
    protected function getDsnFromDriver(){
667
      $config = $this->getDatabaseConfiguration();
668
      if (! empty($config)){
669
        $driver = $config['driver'];
670
        $driverDsnMap = array(
671
                                'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
672
                                            . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
673
                                            . 'dbname=' . $config['database'],
674
                                'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
675
                                            . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
676
                                            . 'dbname=' . $config['database'],
677
                                'sqlite' => 'sqlite:' . $config['database'],
678
                                'oracle' => 'oci:dbname=' . $config['hostname'] 
679
                                            . (($config['port']) != '' ? ':' . $config['port'] : '')
680
                                            . '/' . $config['database']
681
                              );
682
        return isset($driverDsnMap[$driver]) ? $driverDsnMap[$driver] : '';
683
      }                   
684
      return null;
685
    }
686
687
     /**
688
     * Transform the prepared query like (?, ?, ?) into string format
689
     * @see Database::query
690
     *
691
     * @return string
692
     */
693
    protected function getPreparedQuery($query, $data){
694
      if (is_array($data)){
695
  			$x = explode('?', $query);
696
  			$q = '';
697
  			foreach($x as $k => $v){
698
  			  if (! empty($v)){
699
  				  $q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : '');
700
  			  }
701
  			}
702
  			return $q;
703
      }
704
      return $query;
705
    }
706
707
    /**
708
     * Get the cache content for this query
709
     * @see Database::query
710
     *      
711
     * @return mixed
712
     */
713
    protected function getCacheContentForQuery($query, $all, $array){
714
        $cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
715
        if (! is_object($this->getCacheInstance())){
716
    			//can not call method with reference in argument
717
    			//like $this->setCacheInstance(& get_instance()->cache);
718
    			//use temporary variable
719
    			$instance = & get_instance()->cache;
720
    			$this->setCacheInstance($instance);
721
        }
722
        return $this->getCacheInstance()->get($cacheKey);
723
    }
724
725
    /**
726
     * Save the result of query into cache
727
     * @param string $query  the SQL query
728
     * @param string $key    the cache key
729
     * @param mixed $result the query result to save
730
     * @param boolean $status whether can save the query result into cache
731
     * @param int $expire the cache TTL
732
     */
733
     protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
734
        if ($status){
735
            $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
736
            if (! is_object($this->getCacheInstance())){
737
      				//can not call method with reference in argument
738
      				//like $this->setCacheInstance(& get_instance()->cache);
739
      				//use temporary variable
740
      				$instance = & get_instance()->cache;
741
      				$this->setCacheInstance($instance);
742
      			}
743
            $this->getCacheInstance()->set($key, $result, $expire);
744
        }
745
     }
746
747
    
748
    /**
749
     * Set error for database query execution
750
     */
751
    protected function setQueryError(){
752
      $error = $this->pdo->errorInfo();
753
      $this->error = isset($error[2]) ? $error[2] : '';
754
      $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
755
	    //show error message
756
      $this->error();
757
    }
758
759
	  /**
760
     * Return the cache key for the given query
761
     * @see Database::query
762
     * 
763
     *  @return string
764
     */
765
    protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
766
      if (is_array($all)){
767
        $all = 'array';
768
      }
769
      return md5($query . $all . $array);
770
    }
771
    
772
	   /**
773
     * Set the Log instance using argument or create new instance
774
     * @param object $logger the Log instance if not null
775
     */
776
    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
777
      if ($logger !== null){
778
        $this->setLogger($logger);
779
      }
780
      else{
781
          $this->logger =& class_loader('Log', 'classes');
782
          $this->logger->setLogger('Library::Database');
783
      }
784
    }
785
	
786
   /**
787
   * Set the DatabaseQueryBuilder instance using argument or create new instance
788
   * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
789
   */
790
	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
791
	  if ($queryBuilder !== null){
792
      $this->setQueryBuilder($queryBuilder);
793
	  }
794
	  else{
795
		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes');
796
	  }
797
	}
798
799
    /**
800
     * Reset the database class attributs to the initail values before each query.
801
     */
802
    private function reset(){
803
	   //query builder reset
804
      $this->getQueryBuilder()->reset();
805
      $this->numRows  = 0;
806
      $this->insertId = null;
807
      $this->query    = null;
808
      $this->error    = null;
809
      $this->result   = array();
810
      $this->data     = array();
811
    }
812
813
    /**
814
     * The class destructor
815
     */
816
    public function __destruct(){
817
      $this->pdo = null;
818
    }
819
820
}
821