-
Notifications
You must be signed in to change notification settings - Fork 131
/
DboSource.php
executable file
·4740 lines (4231 loc) · 131 KB
/
DboSource.php
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Dbo Source
*
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @package Cake.Model.Datasource
* @since CakePHP(tm) v 0.10.0.1076
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DataSource', 'Model/Datasource');
App::uses('CakeText', 'Utility');
App::uses('View', 'View');
// CUSTOMIZE ADD 2012/11/04 itm_kiyo
// >>>
App::uses('CakeSchema', 'Model');
// <<<
/**
* DboSource
*
* Creates DBO-descendant objects from a given db connection configuration
*
* @package Cake.Model.Datasource
*/
class DboSource extends DataSource {
// >>> CUSTOMIZE ADD 2010/12/17 ryuring
/**
* PHP←→DBエンコーディングマップ
*
* @var array
*/
protected $_encodingMaps = array('utf8' => 'UTF-8', 'sjis' => 'SJIS', 'ujis' => 'EUC-JP');
// <<<
/**
* Description string for this Database Data Source.
*
* @var string
*/
public $description = "Database Data Source";
/**
* index definition, standard cake, primary, index, unique
*
* @var array
*/
public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
/**
* Database keyword used to assign aliases to identifiers.
*
* @var string
*/
public $alias = 'AS ';
/**
* Caches result from query parsing operations. Cached results for both DboSource::name() and DboSource::fields()
* will be stored here.
*
* Method caching uses `md5` (by default) to construct cache keys. If you have problems with collisions,
* try a different hashing algorithm by overriding DboSource::cacheMethodHasher or set DboSource::$cacheMethods to false.
*
* @var array
*/
public static $methodCache = array();
/**
* Whether or not to cache the results of DboSource::name() and DboSource::fields() into the memory cache.
* Set to false to disable the use of the memory cache.
*
* @var bool
*/
public $cacheMethods = true;
/**
* Flag to support nested transactions. If it is set to false, you will be able to use
* the transaction methods (begin/commit/rollback), but just the global transaction will
* be executed.
*
* @var bool
*/
public $useNestedTransactions = false;
/**
* Print full query debug info?
*
* @var bool
*/
public $fullDebug = false;
/**
* String to hold how many rows were affected by the last SQL operation.
*
* @var string
*/
public $affected = null;
/**
* Number of rows in current resultset
*
* @var int
*/
public $numRows = null;
/**
* Time the last query took
*
* @var int
*/
public $took = null;
/**
* Result
*
* @var array|PDOStatement
*/
protected $_result = null;
/**
* Queries count.
*
* @var int
*/
protected $_queriesCnt = 0;
/**
* Total duration of all queries.
*
* @var int
*/
protected $_queriesTime = null;
/**
* Log of queries executed by this DataSource
*
* @var array
*/
protected $_queriesLog = array();
/**
* Maximum number of items in query log
*
* This is to prevent query log taking over too much memory.
*
* @var int
*/
protected $_queriesLogMax = 200;
/**
* Caches serialized results of executed queries
*
* @var array
*/
protected $_queryCache = array();
/**
* A reference to the physical connection of this DataSource
*
* @var array
*/
protected $_connection = null;
/**
* The DataSource configuration key name
*
* @var string
*/
public $configKeyName = null;
/**
* The starting character that this DataSource uses for quoted identifiers.
*
* @var string
*/
public $startQuote = null;
/**
* The ending character that this DataSource uses for quoted identifiers.
*
* @var string
*/
public $endQuote = null;
/**
* The set of valid SQL operations usable in a WHERE statement
*
* @var array
*/
protected $_sqlOps = array('like', 'ilike', 'rlike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
/**
* The set of valid SQL boolean operations usable in a WHERE statement
*
* @var array
*/
protected $_sqlBoolOps = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
/**
* Indicates the level of nested transactions
*
* @var int
*/
protected $_transactionNesting = 0;
/**
* Default fields that are used by the DBO
*
* @var array
*/
protected $_queryDefaults = array(
'conditions' => array(),
'fields' => null,
'table' => null,
'alias' => null,
'order' => null,
'limit' => null,
'joins' => array(),
'group' => null,
'offset' => null,
'having' => null,
'lock' => null,
);
/**
* Separator string for virtualField composition
*
* @var string
*/
public $virtualFieldSeparator = '__';
/**
* List of table engine specific parameters used on table creating
*
* @var array
*/
public $tableParameters = array();
/**
* List of engine specific additional field parameters used on table creating
*
* @var array
*/
public $fieldParameters = array();
/**
* Indicates whether there was a change on the cached results on the methods of this class
* This will be used for storing in a more persistent cache
*
* @var bool
*/
protected $_methodCacheChange = false;
/**
* Map of the columns contained in a result.
*
* @var array
*/
public $map = array();
/**
* Constructor
*
* @param array $config Array of configuration information for the Datasource.
* @param bool $autoConnect Whether or not the datasource should automatically connect.
* @throws MissingConnectionException when a connection cannot be made.
*/
public function __construct($config = null, $autoConnect = true) {
if (!isset($config['prefix'])) {
$config['prefix'] = '';
}
parent::__construct($config);
$this->fullDebug = Configure::read('debug') > 1;
if (!$this->enabled()) {
throw new MissingConnectionException(array(
'class' => get_class($this),
'message' => __d('cake_dev', 'Selected driver is not enabled'),
'enabled' => false
));
}
if ($autoConnect) {
$this->connect();
}
}
/**
* Connects to the database.
*
* @return bool
*/
public function connect() {
// This method is implemented in subclasses
return $this->connected;
}
/**
* Reconnects to database server with optional new settings
*
* @param array $config An array defining the new configuration settings
* @return bool True on success, false on failure
*/
public function reconnect($config = array()) {
$this->disconnect();
$this->setConfig($config);
$this->_sources = null;
return $this->connect();
}
/**
* Disconnects from database.
*
* @return bool Always true
*/
public function disconnect() {
if ($this->_result instanceof PDOStatement) {
$this->_result->closeCursor();
}
$this->_connection = null;
$this->connected = false;
return true;
}
/**
* Get the underlying connection object.
*
* @return PDO
*/
public function getConnection() {
return $this->_connection;
}
/**
* Gets the version string of the database server
*
* @return string The database version
*/
public function getVersion() {
return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
}
/**
* Returns a quoted and escaped string of $data for use in an SQL statement.
*
* @param string $data String to be prepared for use in an SQL statement
* @param string $column The column datatype into which this data will be inserted.
* @param bool $null Column allows NULL values
* @return string Quoted and escaped data
*/
public function value($data, $column = null, $null = true) {
if (is_array($data) && !empty($data)) {
return array_map(
array(&$this, 'value'),
$data, array_fill(0, count($data), $column)
);
} elseif (is_object($data) && isset($data->type, $data->value)) {
if ($data->type === 'identifier') {
return $this->name($data->value);
} elseif ($data->type === 'expression') {
return $data->value;
}
} elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
return $data;
}
if ($data === null || (is_array($data) && empty($data))) {
return 'NULL';
}
if (empty($column)) {
$column = $this->introspectType($data);
}
$isStringEnum = false;
if (strpos($column, "enum") === 0) {
$firstValue = null;
if (preg_match("/(enum\()(.*)(\))/i", $column, $acceptingValues)) {
$values = explode(",", $acceptingValues[2]);
$firstValue = $values[0];
}
if (is_string($firstValue)) {
$isStringEnum = true;
}
}
switch ($column) {
case 'binary':
return $this->_connection->quote($data, PDO::PARAM_LOB);
case 'boolean':
return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
case 'string':
case 'text':
return $this->_connection->quote($data, PDO::PARAM_STR);
default:
if ($data === '') {
return $null ? 'NULL' : '""';
}
if (is_float($data)) {
return str_replace(',', '.', strval($data));
}
if (((is_int($data) || $data === '0') || (
is_numeric($data) &&
strpos($data, ',') === false &&
$data[0] != '0' &&
strpos($data, 'e') === false)
) && !$isStringEnum
) {
return $data;
}
return $this->_connection->quote($data);
}
}
/**
* Returns an object to represent a database identifier in a query. Expression objects
* are not sanitized or escaped.
*
* @param string $identifier A SQL expression to be used as an identifier
* @return stdClass An object representing a database identifier to be used in a query
*/
public function identifier($identifier) {
$obj = new stdClass();
$obj->type = 'identifier';
$obj->value = $identifier;
return $obj;
}
/**
* Returns an object to represent a database expression in a query. Expression objects
* are not sanitized or escaped.
*
* @param string $expression An arbitrary SQL expression to be inserted into a query.
* @return stdClass An object representing a database expression to be used in a query
*/
public function expression($expression) {
$obj = new stdClass();
$obj->type = 'expression';
$obj->value = $expression;
return $obj;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @param array $params Additional options for the query.
* @return mixed Resource or object representing the result set, or false on failure
*/
public function rawQuery($sql, $params = array()) {
$this->took = $this->numRows = false;
return $this->execute($sql, array(), $params);
}
/**
* Queries the database with given SQL statement, and obtains some metadata about the result
* (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
* If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
*
* ### Options
*
* - log - Whether or not the query should be logged to the memory log.
*
* @param string $sql SQL statement
* @param array $options The options for executing the query.
* @param array $params values to be bound to the query.
* @return mixed Resource or object representing the result set, or false on failure
*/
public function execute($sql, $options = array(), $params = array()) {
$options += array('log' => $this->fullDebug);
$t = microtime(true);
$this->_result = $this->_execute($sql, $params);
if ($options['log']) {
$this->took = round((microtime(true) - $t) * 1000, 0);
$this->numRows = $this->affected = $this->lastAffected();
$this->logQuery($sql, $params);
}
return $this->_result;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @param array $params list of params to be bound to query
* @param array $prepareOptions Options to be used in the prepare statement
* @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
* query returning no rows, such as a CREATE statement, false otherwise
* @throws PDOException
*/
protected function _execute($sql, $params = array(), $prepareOptions = array()) {
$sql = trim($sql);
if (preg_match('/^(?:CREATE|ALTER|DROP)\s+(?:TABLE|INDEX)/i', $sql)) {
$statements = array_filter(explode(';', $sql));
if (count($statements) > 1) {
$result = array_map(array($this, '_execute'), $statements);
return array_search(false, $result) === false;
}
}
try {
$query = $this->_connection->prepare($sql, $prepareOptions);
$query->setFetchMode(PDO::FETCH_LAZY);
if (!$query->execute($params)) {
$this->_result = $query;
$query->closeCursor();
return false;
}
if (!$query->columnCount()) {
$query->closeCursor();
if (!$query->rowCount()) {
return true;
}
}
return $query;
} catch (PDOException $e) {
if (isset($query->queryString)) {
$e->queryString = $query->queryString;
} else {
$e->queryString = $sql;
}
throw $e;
}
}
/**
* Returns a formatted error message from previous database operation.
*
* @param PDOStatement $query the query to extract the error from if any
* @return string Error message with error number
*/
public function lastError(PDOStatement $query = null) {
if ($query) {
$error = $query->errorInfo();
} else {
$error = $this->_connection->errorInfo();
}
if (empty($error[2])) {
return null;
}
return $error[1] . ': ' . $error[2];
}
/**
* Returns number of affected rows in previous database operation. If no previous operation exists,
* this returns false.
*
* @param mixed $source The source to check.
* @return int Number of affected rows
*/
public function lastAffected($source = null) {
if ($this->hasResult()) {
return $this->_result->rowCount();
}
return 0;
}
/**
* Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false.
*
* @param mixed $source Not used
* @return int Number of rows in resultset
*/
public function lastNumRows($source = null) {
return $this->lastAffected();
}
/**
* DataSource Query abstraction
*
* @return resource Result resource identifier.
*/
public function query() {
$args = func_get_args();
$fields = null;
$order = null;
$limit = null;
$page = null;
$recursive = null;
if (count($args) === 1) {
return $this->fetchAll($args[0]);
} elseif (count($args) > 1 && preg_match('/^find(\w*)By(.+)/', $args[0], $matches)) {
$params = $args[1];
$findType = lcfirst($matches[1]);
$field = Inflector::underscore($matches[2]);
$or = (strpos($field, '_or_') !== false);
if ($or) {
$field = explode('_or_', $field);
} else {
$field = explode('_and_', $field);
}
$off = count($field) - 1;
if (isset($params[1 + $off])) {
$fields = $params[1 + $off];
}
if (isset($params[2 + $off])) {
$order = $params[2 + $off];
}
if (!array_key_exists(0, $params)) {
return false;
}
$c = 0;
$conditions = array();
foreach ($field as $f) {
$conditions[$args[2]->alias . '.' . $f] = $params[$c++];
}
if ($or) {
$conditions = array('OR' => $conditions);
}
if ($findType !== 'first' && $findType !== '') {
if (isset($params[3 + $off])) {
$limit = $params[3 + $off];
}
if (isset($params[4 + $off])) {
$page = $params[4 + $off];
}
if (isset($params[5 + $off])) {
$recursive = $params[5 + $off];
}
return $args[2]->find($findType, compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
}
if (isset($params[3 + $off])) {
$recursive = $params[3 + $off];
}
return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
}
if (isset($args[1]) && $args[1] === true) {
return $this->fetchAll($args[0], true);
} elseif (isset($args[1]) && !is_array($args[1])) {
return $this->fetchAll($args[0], false);
} elseif (isset($args[1]) && is_array($args[1])) {
if (isset($args[2])) {
$cache = $args[2];
} else {
$cache = true;
}
return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
}
}
/**
* Builds a map of the columns contained in a result
*
* @param PDOStatement $results The results to format.
* @return void
*/
public function resultSet($results) {
// This method is implemented in subclasses
}
/**
* Returns a row from current resultset as an array
*
* @param string $sql Some SQL to be executed.
* @return array The fetched row as an array
*/
public function fetchRow($sql = null) {
if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) {
return null;
}
if ($this->hasResult()) {
$this->resultSet($this->_result);
$resultRow = $this->fetchResult();
if (isset($resultRow[0])) {
$this->fetchVirtualField($resultRow);
}
return $resultRow;
}
return null;
}
/**
* Returns an array of all result rows for a given SQL query.
*
* Returns false if no rows matched.
*
* ### Options
*
* - `cache` - Returns the cached version of the query, if exists and stores the result in cache.
* This is a non-persistent cache, and only lasts for a single request. This option
* defaults to true. If you are directly calling this method, you can disable caching
* by setting $options to `false`
*
* @param string $sql SQL statement
* @param array|bool $params Either parameters to be bound as values for the SQL statement,
* or a boolean to control query caching.
* @param array $options additional options for the query.
* @return bool|array Array of resultset rows, or false if no rows matched
*/
public function fetchAll($sql, $params = array(), $options = array()) {
if (is_string($options)) {
$options = array('modelName' => $options);
}
if (is_bool($params)) {
$options['cache'] = $params;
$params = array();
}
$options += array('cache' => true);
$cache = $options['cache'];
if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
return $cached;
}
$result = $this->execute($sql, array(), $params);
if ($result) {
$out = array();
if ($this->hasResult()) {
$first = $this->fetchRow();
if ($first) {
$out[] = $first;
}
while ($item = $this->fetchResult()) {
if (isset($item[0])) {
$this->fetchVirtualField($item);
}
$out[] = $item;
}
}
if (!is_bool($result) && $cache) {
$this->_writeQueryCache($sql, $out, $params);
}
if (empty($out) && is_bool($this->_result)) {
return $this->_result;
}
return $out;
}
return false;
}
/**
* Fetches the next row from the current result set
*
* @return bool
*/
public function fetchResult() {
return false;
}
/**
* Modifies $result array to place virtual fields in model entry where they belongs to
*
* @param array &$result Reference to the fetched row
* @return void
*/
public function fetchVirtualField(&$result) {
if (isset($result[0]) && is_array($result[0])) {
foreach ($result[0] as $field => $value) {
if (strpos($field, $this->virtualFieldSeparator) === false) {
continue;
}
list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
if (!ClassRegistry::isKeySet($alias)) {
return;
}
$Model = ClassRegistry::getObject($alias);
if ($Model->isVirtualField($virtual)) {
$result[$alias][$virtual] = $value;
unset($result[0][$field]);
}
}
if (empty($result[0])) {
unset($result[0]);
}
}
}
/**
* Returns a single field of the first of query results for a given SQL query, or false if empty.
*
* @param string $name The name of the field to get.
* @param string $sql The SQL query.
* @return mixed Value of field read, or false if not found.
*/
public function field($name, $sql) {
$data = $this->fetchRow($sql);
if (empty($data[$name])) {
return false;
}
return $data[$name];
}
/**
* Empties the method caches.
* These caches are used by DboSource::name() and DboSource::conditions()
*
* @return void
*/
public function flushMethodCache() {
$this->_methodCacheChange = true;
static::$methodCache = array();
}
/**
* Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
* Will retrieve a value from the cache if $value is null.
*
* If caching is disabled and a write is attempted, the $value will be returned.
* A read will either return the value or null.
*
* @param string $method Name of the method being cached.
* @param string $key The key name for the cache operation.
* @param mixed $value The value to cache into memory.
* @return mixed Either null on failure, or the value if its set.
*/
public function cacheMethod($method, $key, $value = null) {
if ($this->cacheMethods === false) {
return $value;
}
if (!$this->_methodCacheChange && empty(static::$methodCache)) {
static::$methodCache = (array)Cache::read('method_cache', '_cake_core_');
}
if ($value === null) {
return (isset(static::$methodCache[$method][$key])) ? static::$methodCache[$method][$key] : null;
}
if (!$this->cacheMethodFilter($method, $key, $value)) {
return $value;
}
$this->_methodCacheChange = true;
return static::$methodCache[$method][$key] = $value;
}
/**
* Filters to apply to the results of `name` and `fields`. When the filter for a given method does not return `true`
* then the result is not added to the memory cache.
*
* Some examples:
*
* ```
* // For method fields, do not cache values that contain floats
* if ($method === 'fields') {
* $hasFloat = preg_grep('/(\d+)?\.\d+/', $value);
*
* return count($hasFloat) === 0;
* }
*
* return true;
* ```
*
* ```
* // For method name, do not cache values that have the name created
* if ($method === 'name') {
* return preg_match('/^`created`$/', $value) !== 1;
* }
*
* return true;
* ```
*
* ```
* // For method name, do not cache values that have the key 472551d38e1f8bbc78d7dfd28106166f
* if ($key === '472551d38e1f8bbc78d7dfd28106166f') {
* return false;
* }
*
* return true;
* ```
*
* @param string $method Name of the method being cached.
* @param string $key The key name for the cache operation.
* @param mixed $value The value to cache into memory.
* @return bool Whether or not to cache
*/
public function cacheMethodFilter($method, $key, $value) {
return true;
}
/**
* Hashes a given value.
*
* Method caching uses `md5` (by default) to construct cache keys. If you have problems with collisions,
* try a different hashing algorithm or set DboSource::$cacheMethods to false.
*
* @param string $value Value to hash
* @return string Hashed value
* @see http://php.net/manual/en/function.hash-algos.php
* @see http://softwareengineering.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed
*/
public function cacheMethodHasher($value) {
return md5($value);
}
/**
* Returns a quoted name of $data for use in an SQL statement.
* Strips fields out of SQL functions before quoting.
*
* Results of this method are stored in a memory cache. This improves performance, but
* because the method uses a hashing algorithm it can have collisions.
* Setting DboSource::$cacheMethods to false will disable the memory cache.
*
* @param mixed $data Either a string with a column to quote. An array of columns to quote or an
* object from DboSource::expression() or DboSource::identifier()
* @return string SQL field
*/
public function name($data) {
if (is_object($data) && isset($data->type)) {
return $data->value;
}
if ($data === '*') {
return '*';
}
if (is_array($data)) {
foreach ($data as $i => $dataItem) {
$data[$i] = $this->name($dataItem);
}
return $data;
}
$cacheKey = $this->cacheMethodHasher($this->startQuote . $data . $this->endQuote);
if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
return $return;
}
$data = trim($data);
if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
if (strpos($data, '.') === false) { // string
return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
}
$items = explode('.', $data);
return $this->cacheMethod(__FUNCTION__, $cacheKey,
$this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
);
}
if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
return $this->cacheMethod(__FUNCTION__, $cacheKey,
$this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
);
}
if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
return $this->cacheMethod(__FUNCTION__, $cacheKey,
$matches[1] . '(' . $this->name($matches[2]) . ')'
);
}
if (preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches)) {
return $this->cacheMethod(
__FUNCTION__, $cacheKey,
preg_replace(
'/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
)
);
}
if (preg_match('/^[\w\-_\s]*[\w\-_]+/', $data)) {
return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
}
return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
}
/**
* Checks if the source is connected to the database.
*
* @return bool True if the database is connected, else false
*/
public function isConnected() {
if ($this->_connection === null) {
$connected = false;
} else {
try {
$connected = $this->_connection->query('SELECT 1');
} catch (Exception $e) {
$connected = false;
}
}
$this->connected = !empty($connected);
return $this->connected;
}
/**
* Checks if the result is valid
*
* @return bool True if the result is valid else false
*/
public function hasResult() {
return $this->_result instanceof PDOStatement;