Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12345 anikendra 1
<?php
2
/**
3
 * Dbo Source
4
 *
5
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
6
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7
 *
8
 * Licensed under The MIT License
9
 * For full copyright and license information, please see the LICENSE.txt
10
 * Redistributions of files must retain the above copyright notice.
11
 *
12
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13
 * @link          http://cakephp.org CakePHP(tm) Project
14
 * @package       Cake.Model.Datasource
15
 * @since         CakePHP(tm) v 0.10.0.1076
16
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
17
 */
18
 
19
App::uses('DataSource', 'Model/Datasource');
20
App::uses('String', 'Utility');
21
App::uses('View', 'View');
22
 
23
/**
24
 * DboSource
25
 *
26
 * Creates DBO-descendant objects from a given db connection configuration
27
 *
28
 * @package       Cake.Model.Datasource
29
 */
30
class DboSource extends DataSource {
31
 
32
/**
33
 * Description string for this Database Data Source.
34
 *
35
 * @var string
36
 */
37
	public $description = "Database Data Source";
38
 
39
/**
40
 * index definition, standard cake, primary, index, unique
41
 *
42
 * @var array
43
 */
44
	public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
45
 
46
/**
47
 * Database keyword used to assign aliases to identifiers.
48
 *
49
 * @var string
50
 */
51
	public $alias = 'AS ';
52
 
53
/**
54
 * Caches result from query parsing operations. Cached results for both DboSource::name() and
55
 * DboSource::conditions() will be stored here. Method caching uses `md5()`. If you have
56
 * problems with collisions, set DboSource::$cacheMethods to false.
57
 *
58
 * @var array
59
 */
60
	public static $methodCache = array();
61
 
62
/**
63
 * Whether or not to cache the results of DboSource::name() and DboSource::conditions()
64
 * into the memory cache. Set to false to disable the use of the memory cache.
65
 *
66
 * @var bool
67
 */
68
	public $cacheMethods = true;
69
 
70
/**
71
 * Flag to support nested transactions. If it is set to false, you will be able to use
72
 * the transaction methods (begin/commit/rollback), but just the global transaction will
73
 * be executed.
74
 *
75
 * @var bool
76
 */
77
	public $useNestedTransactions = false;
78
 
79
/**
80
 * Print full query debug info?
81
 *
82
 * @var bool
83
 */
84
	public $fullDebug = false;
85
 
86
/**
87
 * String to hold how many rows were affected by the last SQL operation.
88
 *
89
 * @var string
90
 */
91
	public $affected = null;
92
 
93
/**
94
 * Number of rows in current resultset
95
 *
96
 * @var int
97
 */
98
	public $numRows = null;
99
 
100
/**
101
 * Time the last query took
102
 *
103
 * @var int
104
 */
105
	public $took = null;
106
 
107
/**
108
 * Result
109
 *
110
 * @var array
111
 */
112
	protected $_result = null;
113
 
114
/**
115
 * Queries count.
116
 *
117
 * @var int
118
 */
119
	protected $_queriesCnt = 0;
120
 
121
/**
122
 * Total duration of all queries.
123
 *
124
 * @var int
125
 */
126
	protected $_queriesTime = null;
127
 
128
/**
129
 * Log of queries executed by this DataSource
130
 *
131
 * @var array
132
 */
133
	protected $_queriesLog = array();
134
 
135
/**
136
 * Maximum number of items in query log
137
 *
138
 * This is to prevent query log taking over too much memory.
139
 *
140
 * @var int
141
 */
142
	protected $_queriesLogMax = 200;
143
 
144
/**
145
 * Caches serialized results of executed queries
146
 *
147
 * @var array
148
 */
149
	protected $_queryCache = array();
150
 
151
/**
152
 * A reference to the physical connection of this DataSource
153
 *
154
 * @var array
155
 */
156
	protected $_connection = null;
157
 
158
/**
159
 * The DataSource configuration key name
160
 *
161
 * @var string
162
 */
163
	public $configKeyName = null;
164
 
165
/**
166
 * The starting character that this DataSource uses for quoted identifiers.
167
 *
168
 * @var string
169
 */
170
	public $startQuote = null;
171
 
172
/**
173
 * The ending character that this DataSource uses for quoted identifiers.
174
 *
175
 * @var string
176
 */
177
	public $endQuote = null;
178
 
179
/**
180
 * The set of valid SQL operations usable in a WHERE statement
181
 *
182
 * @var array
183
 */
184
	protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
185
 
186
/**
187
 * Indicates the level of nested transactions
188
 *
189
 * @var int
190
 */
191
	protected $_transactionNesting = 0;
192
 
193
/**
194
 * Default fields that are used by the DBO
195
 *
196
 * @var array
197
 */
198
	protected $_queryDefaults = array(
199
		'conditions' => array(),
200
		'fields' => null,
201
		'table' => null,
202
		'alias' => null,
203
		'order' => null,
204
		'limit' => null,
205
		'joins' => array(),
206
		'group' => null,
207
		'offset' => null
208
	);
209
 
210
/**
211
 * Separator string for virtualField composition
212
 *
213
 * @var string
214
 */
215
	public $virtualFieldSeparator = '__';
216
 
217
/**
218
 * List of table engine specific parameters used on table creating
219
 *
220
 * @var array
221
 */
222
	public $tableParameters = array();
223
 
224
/**
225
 * List of engine specific additional field parameters used on table creating
226
 *
227
 * @var array
228
 */
229
	public $fieldParameters = array();
230
 
231
/**
232
 * Indicates whether there was a change on the cached results on the methods of this class
233
 * This will be used for storing in a more persistent cache
234
 *
235
 * @var bool
236
 */
237
	protected $_methodCacheChange = false;
238
 
239
/**
240
 * Constructor
241
 *
242
 * @param array $config Array of configuration information for the Datasource.
243
 * @param bool $autoConnect Whether or not the datasource should automatically connect.
244
 * @throws MissingConnectionException when a connection cannot be made.
245
 */
246
	public function __construct($config = null, $autoConnect = true) {
247
		if (!isset($config['prefix'])) {
248
			$config['prefix'] = '';
249
		}
250
		parent::__construct($config);
251
		$this->fullDebug = Configure::read('debug') > 1;
252
		if (!$this->enabled()) {
253
			throw new MissingConnectionException(array(
254
				'class' => get_class($this),
255
				'message' => __d('cake_dev', 'Selected driver is not enabled'),
256
				'enabled' => false
257
			));
258
		}
259
		if ($autoConnect) {
260
			$this->connect();
261
		}
262
	}
263
 
264
/**
265
 * Reconnects to database server with optional new settings
266
 *
267
 * @param array $config An array defining the new configuration settings
268
 * @return bool True on success, false on failure
269
 */
270
	public function reconnect($config = array()) {
271
		$this->disconnect();
272
		$this->setConfig($config);
273
		$this->_sources = null;
274
 
275
		return $this->connect();
276
	}
277
 
278
/**
279
 * Disconnects from database.
280
 *
281
 * @return bool Always true
282
 */
283
	public function disconnect() {
284
		if ($this->_result instanceof PDOStatement) {
285
			$this->_result->closeCursor();
286
		}
287
		unset($this->_connection);
288
		$this->connected = false;
289
		return true;
290
	}
291
 
292
/**
293
 * Get the underlying connection object.
294
 *
295
 * @return PDO
296
 */
297
	public function getConnection() {
298
		return $this->_connection;
299
	}
300
 
301
/**
302
 * Gets the version string of the database server
303
 *
304
 * @return string The database version
305
 */
306
	public function getVersion() {
307
		return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
308
	}
309
 
310
/**
311
 * Returns a quoted and escaped string of $data for use in an SQL statement.
312
 *
313
 * @param string $data String to be prepared for use in an SQL statement
314
 * @param string $column The column datatype into which this data will be inserted.
315
 * @return string Quoted and escaped data
316
 */
317
	public function value($data, $column = null) {
318
		if (is_array($data) && !empty($data)) {
319
			return array_map(
320
				array(&$this, 'value'),
321
				$data, array_fill(0, count($data), $column)
322
			);
323
		} elseif (is_object($data) && isset($data->type, $data->value)) {
324
			if ($data->type === 'identifier') {
325
				return $this->name($data->value);
326
			} elseif ($data->type === 'expression') {
327
				return $data->value;
328
			}
329
		} elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
330
			return $data;
331
		}
332
 
333
		if ($data === null || (is_array($data) && empty($data))) {
334
			return 'NULL';
335
		}
336
 
337
		if (empty($column)) {
338
			$column = $this->introspectType($data);
339
		}
340
 
341
		switch ($column) {
342
			case 'binary':
343
				return $this->_connection->quote($data, PDO::PARAM_LOB);
344
			case 'boolean':
345
				return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
346
			case 'string':
347
			case 'text':
348
				return $this->_connection->quote($data, PDO::PARAM_STR);
349
			default:
350
				if ($data === '') {
351
					return 'NULL';
352
				}
353
				if (is_float($data)) {
354
					return str_replace(',', '.', strval($data));
355
				}
356
				if ((is_int($data) || $data === '0') || (
357
					is_numeric($data) && strpos($data, ',') === false &&
358
					$data[0] != '0' && strpos($data, 'e') === false)
359
				) {
360
					return $data;
361
				}
362
				return $this->_connection->quote($data);
363
		}
364
	}
365
 
366
/**
367
 * Returns an object to represent a database identifier in a query. Expression objects
368
 * are not sanitized or escaped.
369
 *
370
 * @param string $identifier A SQL expression to be used as an identifier
371
 * @return stdClass An object representing a database identifier to be used in a query
372
 */
373
	public function identifier($identifier) {
374
		$obj = new stdClass();
375
		$obj->type = 'identifier';
376
		$obj->value = $identifier;
377
		return $obj;
378
	}
379
 
380
/**
381
 * Returns an object to represent a database expression in a query. Expression objects
382
 * are not sanitized or escaped.
383
 *
384
 * @param string $expression An arbitrary SQL expression to be inserted into a query.
385
 * @return stdClass An object representing a database expression to be used in a query
386
 */
387
	public function expression($expression) {
388
		$obj = new stdClass();
389
		$obj->type = 'expression';
390
		$obj->value = $expression;
391
		return $obj;
392
	}
393
 
394
/**
395
 * Executes given SQL statement.
396
 *
397
 * @param string $sql SQL statement
398
 * @param array $params Additional options for the query.
399
 * @return bool
400
 */
401
	public function rawQuery($sql, $params = array()) {
402
		$this->took = $this->numRows = false;
403
		return $this->execute($sql, $params);
404
	}
405
 
406
/**
407
 * Queries the database with given SQL statement, and obtains some metadata about the result
408
 * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
409
 * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
410
 *
411
 * ### Options
412
 *
413
 * - log - Whether or not the query should be logged to the memory log.
414
 *
415
 * @param string $sql SQL statement
416
 * @param array $options The options for executing the query.
417
 * @param array $params values to be bound to the query.
418
 * @return mixed Resource or object representing the result set, or false on failure
419
 */
420
	public function execute($sql, $options = array(), $params = array()) {
421
		$options += array('log' => $this->fullDebug);
422
 
423
		$t = microtime(true);
424
		$this->_result = $this->_execute($sql, $params);
425
 
426
		if ($options['log']) {
427
			$this->took = round((microtime(true) - $t) * 1000, 0);
428
			$this->numRows = $this->affected = $this->lastAffected();
429
			$this->logQuery($sql, $params);
430
		}
431
 
432
		return $this->_result;
433
	}
434
 
435
/**
436
 * Executes given SQL statement.
437
 *
438
 * @param string $sql SQL statement
439
 * @param array $params list of params to be bound to query
440
 * @param array $prepareOptions Options to be used in the prepare statement
441
 * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
442
 * query returning no rows, such as a CREATE statement, false otherwise
443
 * @throws PDOException
444
 */
445
	protected function _execute($sql, $params = array(), $prepareOptions = array()) {
446
		$sql = trim($sql);
447
		if (preg_match('/^(?:CREATE|ALTER|DROP)\s+(?:TABLE|INDEX)/i', $sql)) {
448
			$statements = array_filter(explode(';', $sql));
449
			if (count($statements) > 1) {
450
				$result = array_map(array($this, '_execute'), $statements);
451
				return array_search(false, $result) === false;
452
			}
453
		}
454
 
455
		try {
456
			$query = $this->_connection->prepare($sql, $prepareOptions);
457
			$query->setFetchMode(PDO::FETCH_LAZY);
458
			if (!$query->execute($params)) {
459
				$this->_results = $query;
460
				$query->closeCursor();
461
				return false;
462
			}
463
			if (!$query->columnCount()) {
464
				$query->closeCursor();
465
				if (!$query->rowCount()) {
466
					return true;
467
				}
468
			}
469
			return $query;
470
		} catch (PDOException $e) {
471
			if (isset($query->queryString)) {
472
				$e->queryString = $query->queryString;
473
			} else {
474
				$e->queryString = $sql;
475
			}
476
			throw $e;
477
		}
478
	}
479
 
480
/**
481
 * Returns a formatted error message from previous database operation.
482
 *
483
 * @param PDOStatement $query the query to extract the error from if any
484
 * @return string Error message with error number
485
 */
486
	public function lastError(PDOStatement $query = null) {
487
		if ($query) {
488
			$error = $query->errorInfo();
489
		} else {
490
			$error = $this->_connection->errorInfo();
491
		}
492
		if (empty($error[2])) {
493
			return null;
494
		}
495
		return $error[1] . ': ' . $error[2];
496
	}
497
 
498
/**
499
 * Returns number of affected rows in previous database operation. If no previous operation exists,
500
 * this returns false.
501
 *
502
 * @param mixed $source The source to check.
503
 * @return int Number of affected rows
504
 */
505
	public function lastAffected($source = null) {
506
		if ($this->hasResult()) {
507
			return $this->_result->rowCount();
508
		}
509
		return 0;
510
	}
511
 
512
/**
513
 * Returns number of rows in previous resultset. If no previous resultset exists,
514
 * this returns false.
515
 *
516
 * @param mixed $source Not used
517
 * @return int Number of rows in resultset
518
 */
519
	public function lastNumRows($source = null) {
520
		return $this->lastAffected();
521
	}
522
 
523
/**
524
 * DataSource Query abstraction
525
 *
526
 * @return resource Result resource identifier.
527
 */
528
	public function query() {
529
		$args = func_get_args();
530
		$fields = null;
531
		$order = null;
532
		$limit = null;
533
		$page = null;
534
		$recursive = null;
535
 
536
		if (count($args) === 1) {
537
			return $this->fetchAll($args[0]);
538
		} elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
539
			$params = $args[1];
540
 
541
			if (substr($args[0], 0, 6) === 'findBy') {
542
				$all = false;
543
				$field = Inflector::underscore(substr($args[0], 6));
544
			} else {
545
				$all = true;
546
				$field = Inflector::underscore(substr($args[0], 9));
547
			}
548
 
549
			$or = (strpos($field, '_or_') !== false);
550
			if ($or) {
551
				$field = explode('_or_', $field);
552
			} else {
553
				$field = explode('_and_', $field);
554
			}
555
			$off = count($field) - 1;
556
 
557
			if (isset($params[1 + $off])) {
558
				$fields = $params[1 + $off];
559
			}
560
 
561
			if (isset($params[2 + $off])) {
562
				$order = $params[2 + $off];
563
			}
564
 
565
			if (!array_key_exists(0, $params)) {
566
				return false;
567
			}
568
 
569
			$c = 0;
570
			$conditions = array();
571
 
572
			foreach ($field as $f) {
573
				$conditions[$args[2]->alias . '.' . $f] = $params[$c++];
574
			}
575
 
576
			if ($or) {
577
				$conditions = array('OR' => $conditions);
578
			}
579
 
580
			if ($all) {
581
				if (isset($params[3 + $off])) {
582
					$limit = $params[3 + $off];
583
				}
584
 
585
				if (isset($params[4 + $off])) {
586
					$page = $params[4 + $off];
587
				}
588
 
589
				if (isset($params[5 + $off])) {
590
					$recursive = $params[5 + $off];
591
				}
592
				return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
593
			}
594
			if (isset($params[3 + $off])) {
595
				$recursive = $params[3 + $off];
596
			}
597
			return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
598
		}
599
		if (isset($args[1]) && $args[1] === true) {
600
			return $this->fetchAll($args[0], true);
601
		} elseif (isset($args[1]) && !is_array($args[1])) {
602
			return $this->fetchAll($args[0], false);
603
		} elseif (isset($args[1]) && is_array($args[1])) {
604
			if (isset($args[2])) {
605
				$cache = $args[2];
606
			} else {
607
				$cache = true;
608
			}
609
			return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
610
		}
611
	}
612
 
613
/**
614
 * Returns a row from current resultset as an array
615
 *
616
 * @param string $sql Some SQL to be executed.
617
 * @return array The fetched row as an array
618
 */
619
	public function fetchRow($sql = null) {
620
		if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) {
621
			return null;
622
		}
623
 
624
		if ($this->hasResult()) {
625
			$this->resultSet($this->_result);
626
			$resultRow = $this->fetchResult();
627
			if (isset($resultRow[0])) {
628
				$this->fetchVirtualField($resultRow);
629
			}
630
			return $resultRow;
631
		}
632
		return null;
633
	}
634
 
635
/**
636
 * Returns an array of all result rows for a given SQL query.
637
 *
638
 * Returns false if no rows matched.
639
 *
640
 * ### Options
641
 *
642
 * - `cache` - Returns the cached version of the query, if exists and stores the result in cache.
643
 *   This is a non-persistent cache, and only lasts for a single request. This option
644
 *   defaults to true. If you are directly calling this method, you can disable caching
645
 *   by setting $options to `false`
646
 *
647
 * @param string $sql SQL statement
648
 * @param array|bool $params Either parameters to be bound as values for the SQL statement,
649
 *  or a boolean to control query caching.
650
 * @param array $options additional options for the query.
651
 * @return bool|array Array of resultset rows, or false if no rows matched
652
 */
653
	public function fetchAll($sql, $params = array(), $options = array()) {
654
		if (is_string($options)) {
655
			$options = array('modelName' => $options);
656
		}
657
		if (is_bool($params)) {
658
			$options['cache'] = $params;
659
			$params = array();
660
		}
661
		$options += array('cache' => true);
662
		$cache = $options['cache'];
663
		if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
664
			return $cached;
665
		}
666
		$result = $this->execute($sql, array(), $params);
667
		if ($result) {
668
			$out = array();
669
 
670
			if ($this->hasResult()) {
671
				$first = $this->fetchRow();
672
				if ($first) {
673
					$out[] = $first;
674
				}
675
				while ($item = $this->fetchResult()) {
676
					if (isset($item[0])) {
677
						$this->fetchVirtualField($item);
678
					}
679
					$out[] = $item;
680
				}
681
			}
682
 
683
			if (!is_bool($result) && $cache) {
684
				$this->_writeQueryCache($sql, $out, $params);
685
			}
686
 
687
			if (empty($out) && is_bool($this->_result)) {
688
				return $this->_result;
689
			}
690
			return $out;
691
		}
692
		return false;
693
	}
694
 
695
/**
696
 * Fetches the next row from the current result set
697
 *
698
 * @return bool
699
 */
700
	public function fetchResult() {
701
		return false;
702
	}
703
 
704
/**
705
 * Modifies $result array to place virtual fields in model entry where they belongs to
706
 *
707
 * @param array &$result Reference to the fetched row
708
 * @return void
709
 */
710
	public function fetchVirtualField(&$result) {
711
		if (isset($result[0]) && is_array($result[0])) {
712
			foreach ($result[0] as $field => $value) {
713
				if (strpos($field, $this->virtualFieldSeparator) === false) {
714
					continue;
715
				}
716
 
717
				list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
718
 
719
				if (!ClassRegistry::isKeySet($alias)) {
720
					return;
721
				}
722
 
723
				$Model = ClassRegistry::getObject($alias);
724
 
725
				if ($Model->isVirtualField($virtual)) {
726
					$result[$alias][$virtual] = $value;
727
					unset($result[0][$field]);
728
				}
729
			}
730
			if (empty($result[0])) {
731
				unset($result[0]);
732
			}
733
		}
734
	}
735
 
736
/**
737
 * Returns a single field of the first of query results for a given SQL query, or false if empty.
738
 *
739
 * @param string $name Name of the field
740
 * @param string $sql SQL query
741
 * @return mixed Value of field read.
742
 */
743
	public function field($name, $sql) {
744
		$data = $this->fetchRow($sql);
745
		if (empty($data[$name])) {
746
			return false;
747
		}
748
		return $data[$name];
749
	}
750
 
751
/**
752
 * Empties the method caches.
753
 * These caches are used by DboSource::name() and DboSource::conditions()
754
 *
755
 * @return void
756
 */
757
	public function flushMethodCache() {
758
		$this->_methodCacheChange = true;
759
		self::$methodCache = array();
760
	}
761
 
762
/**
763
 * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
764
 * Will retrieve a value from the cache if $value is null.
765
 *
766
 * If caching is disabled and a write is attempted, the $value will be returned.
767
 * A read will either return the value or null.
768
 *
769
 * @param string $method Name of the method being cached.
770
 * @param string $key The key name for the cache operation.
771
 * @param mixed $value The value to cache into memory.
772
 * @return mixed Either null on failure, or the value if its set.
773
 */
774
	public function cacheMethod($method, $key, $value = null) {
775
		if ($this->cacheMethods === false) {
776
			return $value;
777
		}
778
		if (!$this->_methodCacheChange && empty(self::$methodCache)) {
779
			self::$methodCache = Cache::read('method_cache', '_cake_core_');
780
		}
781
		if ($value === null) {
782
			return (isset(self::$methodCache[$method][$key])) ? self::$methodCache[$method][$key] : null;
783
		}
784
		$this->_methodCacheChange = true;
785
		return self::$methodCache[$method][$key] = $value;
786
	}
787
 
788
/**
789
 * Returns a quoted name of $data for use in an SQL statement.
790
 * Strips fields out of SQL functions before quoting.
791
 *
792
 * Results of this method are stored in a memory cache. This improves performance, but
793
 * because the method uses a hashing algorithm it can have collisions.
794
 * Setting DboSource::$cacheMethods to false will disable the memory cache.
795
 *
796
 * @param mixed $data Either a string with a column to quote. An array of columns to quote or an
797
 *   object from DboSource::expression() or DboSource::identifier()
798
 * @return string SQL field
799
 */
800
	public function name($data) {
801
		if (is_object($data) && isset($data->type)) {
802
			return $data->value;
803
		}
804
		if ($data === '*') {
805
			return '*';
806
		}
807
		if (is_array($data)) {
808
			foreach ($data as $i => $dataItem) {
809
				$data[$i] = $this->name($dataItem);
810
			}
811
			return $data;
812
		}
813
		$cacheKey = md5($this->startQuote . $data . $this->endQuote);
814
		if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
815
			return $return;
816
		}
817
		$data = trim($data);
818
		if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
819
			if (strpos($data, '.') === false) { // string
820
				return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
821
			}
822
			$items = explode('.', $data);
823
			return $this->cacheMethod(__FUNCTION__, $cacheKey,
824
				$this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
825
			);
826
		}
827
		if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
828
			return $this->cacheMethod(__FUNCTION__, $cacheKey,
829
				$this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
830
			);
831
		}
832
		if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
833
			return $this->cacheMethod(__FUNCTION__, $cacheKey,
834
				$matches[1] . '(' . $this->name($matches[2]) . ')'
835
			);
836
		}
837
		if (
838
			preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches
839
		)) {
840
			return $this->cacheMethod(
841
				__FUNCTION__, $cacheKey,
842
				preg_replace(
843
					'/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
844
				)
845
			);
846
		}
847
		if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) {
848
			return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
849
		}
850
		return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
851
	}
852
 
853
/**
854
 * Checks if the source is connected to the database.
855
 *
856
 * @return bool True if the database is connected, else false
857
 */
858
	public function isConnected() {
859
		return $this->connected;
860
	}
861
 
862
/**
863
 * Checks if the result is valid
864
 *
865
 * @return bool True if the result is valid else false
866
 */
867
	public function hasResult() {
868
		return $this->_result instanceof PDOStatement;
869
	}
870
 
871
/**
872
 * Get the query log as an array.
873
 *
874
 * @param bool $sorted Get the queries sorted by time taken, defaults to false.
875
 * @param bool $clear If True the existing log will cleared.
876
 * @return array Array of queries run as an array
877
 */
878
	public function getLog($sorted = false, $clear = true) {
879
		if ($sorted) {
880
			$log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
881
		} else {
882
			$log = $this->_queriesLog;
883
		}
884
		if ($clear) {
885
			$this->_queriesLog = array();
886
		}
887
		return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
888
	}
889
 
890
/**
891
 * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
892
 * will be rendered and output. If in a CLI environment, a plain text log is generated.
893
 *
894
 * @param bool $sorted Get the queries sorted by time taken, defaults to false.
895
 * @return void
896
 */
897
	public function showLog($sorted = false) {
898
		$log = $this->getLog($sorted, false);
899
		if (empty($log['log'])) {
900
			return;
901
		}
902
		if (PHP_SAPI !== 'cli') {
903
			$controller = null;
904
			$View = new View($controller, false);
905
			$View->set('sqlLogs', array($this->configKeyName => $log));
906
			echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
907
		} else {
908
			foreach ($log['log'] as $k => $i) {
909
				print (($k + 1) . ". {$i['query']}\n");
910
			}
911
		}
912
	}
913
 
914
/**
915
 * Log given SQL query.
916
 *
917
 * @param string $sql SQL statement
918
 * @param array $params Values binded to the query (prepared statements)
919
 * @return void
920
 */
921
	public function logQuery($sql, $params = array()) {
922
		$this->_queriesCnt++;
923
		$this->_queriesTime += $this->took;
924
		$this->_queriesLog[] = array(
925
			'query' => $sql,
926
			'params' => $params,
927
			'affected' => $this->affected,
928
			'numRows' => $this->numRows,
929
			'took' => $this->took
930
		);
931
		if (count($this->_queriesLog) > $this->_queriesLogMax) {
932
			array_shift($this->_queriesLog);
933
		}
934
	}
935
 
936
/**
937
 * Gets full table name including prefix
938
 *
939
 * @param Model|string $model Either a Model object or a string table name.
940
 * @param bool $quote Whether you want the table name quoted.
941
 * @param bool $schema Whether you want the schema name included.
942
 * @return string Full quoted table name
943
 */
944
	public function fullTableName($model, $quote = true, $schema = true) {
945
		if (is_object($model)) {
946
			$schemaName = $model->schemaName;
947
			$table = $model->tablePrefix . $model->table;
948
		} elseif (!empty($this->config['prefix']) && strpos($model, $this->config['prefix']) !== 0) {
949
			$table = $this->config['prefix'] . strval($model);
950
		} else {
951
			$table = strval($model);
952
		}
953
 
954
		if ($schema && !isset($schemaName)) {
955
			$schemaName = $this->getSchemaName();
956
		}
957
 
958
		if ($quote) {
959
			if ($schema && !empty($schemaName)) {
960
				if (strstr($table, '.') === false) {
961
					return $this->name($schemaName) . '.' . $this->name($table);
962
				}
963
			}
964
			return $this->name($table);
965
		}
966
 
967
		if ($schema && !empty($schemaName)) {
968
			if (strstr($table, '.') === false) {
969
				return $schemaName . '.' . $table;
970
			}
971
		}
972
 
973
		return $table;
974
	}
975
 
976
/**
977
 * The "C" in CRUD
978
 *
979
 * Creates new records in the database.
980
 *
981
 * @param Model $Model Model object that the record is for.
982
 * @param array $fields An array of field names to insert. If null, $Model->data will be
983
 *   used to generate field names.
984
 * @param array $values An array of values with keys matching the fields. If null, $Model->data will
985
 *   be used to generate values.
986
 * @return bool Success
987
 */
988
	public function create(Model $Model, $fields = null, $values = null) {
989
		$id = null;
990
 
991
		if (!$fields) {
992
			unset($fields, $values);
993
			$fields = array_keys($Model->data);
994
			$values = array_values($Model->data);
995
		}
996
		$count = count($fields);
997
 
998
		for ($i = 0; $i < $count; $i++) {
999
			$valueInsert[] = $this->value($values[$i], $Model->getColumnType($fields[$i]));
1000
			$fieldInsert[] = $this->name($fields[$i]);
1001
			if ($fields[$i] === $Model->primaryKey) {
1002
				$id = $values[$i];
1003
			}
1004
		}
1005
 
1006
		$query = array(
1007
			'table' => $this->fullTableName($Model),
1008
			'fields' => implode(', ', $fieldInsert),
1009
			'values' => implode(', ', $valueInsert)
1010
		);
1011
 
1012
		if ($this->execute($this->renderStatement('create', $query))) {
1013
			if (empty($id)) {
1014
				$id = $this->lastInsertId($this->fullTableName($Model, false, false), $Model->primaryKey);
1015
			}
1016
			$Model->setInsertID($id);
1017
			$Model->id = $id;
1018
			return true;
1019
		}
1020
 
1021
		$Model->onError();
1022
		return false;
1023
	}
1024
 
1025
/**
1026
 * The "R" in CRUD
1027
 *
1028
 * Reads record(s) from the database.
1029
 *
1030
 * @param Model $Model A Model object that the query is for.
1031
 * @param array $queryData An array of queryData information containing keys similar to Model::find().
1032
 * @param int $recursive Number of levels of association
1033
 * @return mixed boolean false on error/failure. An array of results on success.
1034
 */
1035
	public function read(Model $Model, $queryData = array(), $recursive = null) {
1036
		$queryData = $this->_scrubQueryData($queryData);
1037
 
1038
		$array = array('callbacks' => $queryData['callbacks']);
1039
 
1040
		if ($recursive === null && isset($queryData['recursive'])) {
1041
			$recursive = $queryData['recursive'];
1042
		}
1043
 
1044
		if ($recursive !== null) {
1045
			$modelRecursive = $Model->recursive;
1046
			$Model->recursive = $recursive;
1047
		}
1048
 
1049
		if (!empty($queryData['fields'])) {
1050
			$noAssocFields = true;
1051
			$queryData['fields'] = $this->fields($Model, null, $queryData['fields']);
1052
		} else {
1053
			$noAssocFields = false;
1054
			$queryData['fields'] = $this->fields($Model);
1055
		}
1056
 
1057
		if ($Model->recursive === -1) {
1058
			// Primary model data only, no joins.
1059
			$associations = array();
1060
 
1061
		} else {
1062
			$associations = $Model->associations();
1063
 
1064
			if ($Model->recursive === 0) {
1065
				// Primary model data and its domain.
1066
				unset($associations[2], $associations[3]);
1067
			}
1068
		}
1069
 
1070
		$originalJoins = $queryData['joins'];
1071
		$queryData['joins'] = array();
1072
 
1073
		// Generate hasOne and belongsTo associations inside $queryData
1074
		$linkedModels = array();
1075
		foreach ($associations as $type) {
1076
			if ($type !== 'hasOne' && $type !== 'belongsTo') {
1077
				continue;
1078
			}
1079
 
1080
			foreach ($Model->{$type} as $assoc => $assocData) {
1081
				$LinkModel = $Model->{$assoc};
1082
 
1083
				if ($Model->useDbConfig !== $LinkModel->useDbConfig) {
1084
					continue;
1085
				}
1086
 
1087
				if ($noAssocFields) {
1088
					$assocData['fields'] = false;
1089
				}
1090
 
1091
				$external = isset($assocData['external']);
1092
 
1093
				if ($this->generateAssociationQuery($Model, $LinkModel, $type, $assoc, $assocData, $queryData, $external) === true) {
1094
					$linkedModels[$type . '/' . $assoc] = true;
1095
				}
1096
			}
1097
		}
1098
 
1099
		if (!empty($originalJoins)) {
1100
			$queryData['joins'] = array_merge($queryData['joins'], $originalJoins);
1101
		}
1102
 
1103
		// Build SQL statement with the primary model, plus hasOne and belongsTo associations
1104
		$query = $this->buildAssociationQuery($Model, $queryData);
1105
 
1106
		$resultSet = $this->fetchAll($query, $Model->cacheQueries);
1107
		unset($query);
1108
 
1109
		if ($resultSet === false) {
1110
			$Model->onError();
1111
			return false;
1112
		}
1113
 
1114
		$filtered = array();
1115
 
1116
		// Filter hasOne and belongsTo associations
1117
		if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
1118
			$filtered = $this->_filterResults($resultSet, $Model);
1119
		}
1120
 
1121
		// Deep associations
1122
		if ($Model->recursive > -1) {
1123
			$joined = array();
1124
			if (isset($queryData['joins'][0]['alias'])) {
1125
				$joined[$Model->alias] = (array)Hash::extract($queryData['joins'], '{n}.alias');
1126
			}
1127
 
1128
			foreach ($associations as $type) {
1129
				foreach ($Model->{$type} as $assoc => $assocData) {
1130
					$LinkModel = $Model->{$assoc};
1131
 
1132
					if (!isset($linkedModels[$type . '/' . $assoc])) {
1133
						$db = $Model->useDbConfig === $LinkModel->useDbConfig ? $this : $LinkModel->getDataSource();
1134
					} elseif ($Model->recursive > 1) {
1135
						$db = $this;
1136
					}
1137
 
1138
					if (isset($db) && method_exists($db, 'queryAssociation')) {
1139
						$stack = array($assoc);
1140
						$stack['_joined'] = $joined;
1141
 
1142
						$db->queryAssociation($Model, $LinkModel, $type, $assoc, $assocData, $array, true, $resultSet, $Model->recursive - 1, $stack);
1143
						unset($db);
1144
 
1145
						if ($type === 'hasMany' || $type === 'hasAndBelongsToMany') {
1146
							$filtered[] = $assoc;
1147
						}
1148
					}
1149
				}
1150
			}
1151
 
1152
			if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
1153
				$this->_filterResults($resultSet, $Model, $filtered);
1154
			}
1155
		}
1156
 
1157
		if ($recursive !== null) {
1158
			$Model->recursive = $modelRecursive;
1159
		}
1160
 
1161
		return $resultSet;
1162
	}
1163
 
1164
/**
1165
 * Passes association results through afterFind filters of the corresponding model.
1166
 *
1167
 * The primary model is always excluded, because the filtering is later done by Model::_filterResults().
1168
 *
1169
 * @param array &$resultSet Reference of resultset to be filtered.
1170
 * @param Model $Model Instance of model to operate against.
1171
 * @param array $filtered List of classes already filtered, to be skipped.
1172
 * @return array Array of results that have been filtered through $Model->afterFind.
1173
 */
1174
	protected function _filterResults(&$resultSet, Model $Model, $filtered = array()) {
1175
		if (!is_array($resultSet)) {
1176
			return array();
1177
		}
1178
 
1179
		$current = reset($resultSet);
1180
		if (!is_array($current)) {
1181
			return array();
1182
		}
1183
 
1184
		$keys = array_diff(array_keys($current), $filtered, array($Model->alias));
1185
		$filtering = array();
1186
 
1187
		foreach ($keys as $className) {
1188
			if (!isset($Model->{$className}) || !is_object($Model->{$className})) {
1189
				continue;
1190
			}
1191
 
1192
			$LinkedModel = $Model->{$className};
1193
			$filtering[] = $className;
1194
 
1195
			foreach ($resultSet as $key => &$result) {
1196
				$data = $LinkedModel->afterFind(array(array($className => $result[$className])), false);
1197
				if (isset($data[0][$className])) {
1198
					$result[$className] = $data[0][$className];
1199
				} else {
1200
					unset($resultSet[$key]);
1201
				}
1202
			}
1203
		}
1204
 
1205
		return $filtering;
1206
	}
1207
 
1208
/**
1209
 * Queries associations.
1210
 *
1211
 * Used to fetch results on recursive models.
1212
 *
1213
 * - 'hasMany' associations with no limit set:
1214
 *    Fetch, filter and merge is done recursively for every level.
1215
 *
1216
 * - 'hasAndBelongsToMany' associations:
1217
 *    Fetch and filter is done unaffected by the (recursive) level set.
1218
 *
1219
 * @param Model $Model Primary Model object.
1220
 * @param Model $LinkModel Linked model object.
1221
 * @param string $type Association type, one of the model association types ie. hasMany.
1222
 * @param string $association Association name.
1223
 * @param array $assocData Association data.
1224
 * @param array &$queryData An array of queryData information containing keys similar to Model::find().
1225
 * @param bool $external Whether or not the association query is on an external datasource.
1226
 * @param array &$resultSet Existing results.
1227
 * @param int $recursive Number of levels of association.
1228
 * @param array $stack A list with joined models.
1229
 * @return mixed
1230
 * @throws CakeException when results cannot be created.
1231
 */
1232
	public function queryAssociation(Model $Model, Model $LinkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
1233
		if (isset($stack['_joined'])) {
1234
			$joined = $stack['_joined'];
1235
			unset($stack['_joined']);
1236
		}
1237
 
1238
		$queryTemplate = $this->generateAssociationQuery($Model, $LinkModel, $type, $association, $assocData, $queryData, $external);
1239
		if (empty($queryTemplate)) {
1240
			return;
1241
		}
1242
 
1243
		if (!is_array($resultSet)) {
1244
			throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($Model)));
1245
		}
1246
 
1247
		if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
1248
			// 'hasMany' associations with no limit set.
1249
 
1250
			$assocIds = array();
1251
			foreach ($resultSet as $result) {
1252
				$assocIds[] = $this->insertQueryData('{$__cakeID__$}', $result, $association, $Model, $stack);
1253
			}
1254
			$assocIds = array_filter($assocIds);
1255
 
1256
			// Fetch
1257
			$assocResultSet = array();
1258
			if (!empty($assocIds)) {
1259
				$assocResultSet = $this->_fetchHasMany($Model, $queryTemplate, $assocIds);
1260
			}
1261
 
1262
			// Recursively query associations
1263
			if ($recursive > 0 && !empty($assocResultSet) && is_array($assocResultSet)) {
1264
				foreach ($LinkModel->associations() as $type1) {
1265
					foreach ($LinkModel->{$type1} as $assoc1 => $assocData1) {
1266
						$DeepModel = $LinkModel->{$assoc1};
1267
						$tmpStack = $stack;
1268
						$tmpStack[] = $assoc1;
1269
 
1270
						$db = $LinkModel->useDbConfig === $DeepModel->useDbConfig ? $this : $DeepModel->getDataSource();
1271
 
1272
						$db->queryAssociation($LinkModel, $DeepModel, $type1, $assoc1, $assocData1, $queryData, true, $assocResultSet, $recursive - 1, $tmpStack);
1273
					}
1274
				}
1275
			}
1276
 
1277
			// Filter
1278
			if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
1279
				$this->_filterResults($assocResultSet, $Model);
1280
			}
1281
 
1282
			// Merge
1283
			return $this->_mergeHasMany($resultSet, $assocResultSet, $association, $Model);
1284
 
1285
		} elseif ($type === 'hasAndBelongsToMany') {
1286
			// 'hasAndBelongsToMany' associations.
1287
 
1288
			$assocIds = array();
1289
			foreach ($resultSet as $result) {
1290
				$assocIds[] = $this->insertQueryData('{$__cakeID__$}', $result, $association, $Model, $stack);
1291
			}
1292
			$assocIds = array_filter($assocIds);
1293
 
1294
			// Fetch
1295
			$assocResultSet = array();
1296
			if (!empty($assocIds)) {
1297
				$assocResultSet = $this->_fetchHasAndBelongsToMany($Model, $queryTemplate, $assocIds, $association);
1298
			}
1299
 
1300
			$habtmAssocData = $Model->hasAndBelongsToMany[$association];
1301
			$foreignKey = $habtmAssocData['foreignKey'];
1302
			$joinKeys = array($foreignKey, $habtmAssocData['associationForeignKey']);
1303
			list($with, $habtmFields) = $Model->joinModel($habtmAssocData['with'], $joinKeys);
1304
			$habtmFieldsCount = count($habtmFields);
1305
 
1306
			// Filter
1307
			if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
1308
				$this->_filterResults($assocResultSet, $Model);
1309
			}
1310
		}
1311
 
1312
		$modelAlias = $Model->alias;
1313
		$primaryKey = $Model->primaryKey;
1314
		$selfJoin = ($Model->name === $LinkModel->name);
1315
 
1316
		foreach ($resultSet as &$row) {
1317
			if ($type === 'hasOne' || $type === 'belongsTo' || $type === 'hasMany') {
1318
				$assocResultSet = array();
1319
 
1320
				if (
1321
					($type === 'hasOne' || $type === 'belongsTo') &&
1322
					isset($row[$LinkModel->alias], $joined[$Model->alias]) &&
1323
					in_array($LinkModel->alias, $joined[$Model->alias])
1324
				) {
1325
					$joinedData = Hash::filter($row[$LinkModel->alias]);
1326
					if (!empty($joinedData)) {
1327
						$assocResultSet[0] = array($LinkModel->alias => $row[$LinkModel->alias]);
1328
					}
1329
				} else {
1330
					$query = $this->insertQueryData($queryTemplate, $row, $association, $Model, $stack);
1331
					if ($query !== false) {
1332
						$assocResultSet = $this->fetchAll($query, $Model->cacheQueries);
1333
					}
1334
				}
1335
			}
1336
 
1337
			if (!empty($assocResultSet) && is_array($assocResultSet)) {
1338
				if ($recursive > 0) {
1339
					foreach ($LinkModel->associations() as $type1) {
1340
						foreach ($LinkModel->{$type1} as $assoc1 => $assocData1) {
1341
							$DeepModel = $LinkModel->{$assoc1};
1342
 
1343
							if (
1344
								$type1 === 'belongsTo' ||
1345
								($type === 'belongsTo' && $DeepModel->alias === $modelAlias) ||
1346
								($DeepModel->alias !== $modelAlias)
1347
							) {
1348
								$tmpStack = $stack;
1349
								$tmpStack[] = $assoc1;
1350
 
1351
								$db = $LinkModel->useDbConfig === $DeepModel->useDbConfig ? $this : $DeepModel->getDataSource();
1352
 
1353
								$db->queryAssociation($LinkModel, $DeepModel, $type1, $assoc1, $assocData1, $queryData, true, $assocResultSet, $recursive - 1, $tmpStack);
1354
							}
1355
						}
1356
					}
1357
				}
1358
 
1359
				if ($type === 'hasAndBelongsToMany') {
1360
					$merge = array();
1361
					foreach ($assocResultSet as $data) {
1362
						if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$primaryKey]) {
1363
							if ($habtmFieldsCount <= 2) {
1364
								unset($data[$with]);
1365
							}
1366
							$merge[] = $data;
1367
						}
1368
					}
1369
 
1370
					if (empty($merge) && !isset($row[$association])) {
1371
						$row[$association] = $merge;
1372
					} else {
1373
						$this->_mergeAssociation($row, $merge, $association, $type);
1374
					}
1375
				} else {
1376
					$this->_mergeAssociation($row, $assocResultSet, $association, $type, $selfJoin);
1377
				}
1378
 
1379
				if ($type !== 'hasAndBelongsToMany' && isset($row[$association])) {
1380
					$row[$association] = $LinkModel->afterFind($row[$association], false);
1381
				}
1382
 
1383
			} else {
1384
				$tempArray[0][$association] = false;
1385
				$this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
1386
			}
1387
		}
1388
	}
1389
 
1390
/**
1391
 * Fetch 'hasMany' associations.
1392
 *
1393
 * This is just a proxy to maintain BC.
1394
 *
1395
 * @param Model $Model Primary model object.
1396
 * @param string $query Association query template.
1397
 * @param array $ids Array of IDs of associated records.
1398
 * @return array Association results.
1399
 * @see DboSource::_fetchHasMany()
1400
 */
1401
	public function fetchAssociated(Model $Model, $query, $ids) {
1402
		return $this->_fetchHasMany($Model, $query, $ids);
1403
	}
1404
 
1405
/**
1406
 * Fetch 'hasMany' associations.
1407
 *
1408
 * @param Model $Model Primary model object.
1409
 * @param string $query Association query template.
1410
 * @param array $ids Array of IDs of associated records.
1411
 * @return array Association results.
1412
 */
1413
	protected function _fetchHasMany(Model $Model, $query, $ids) {
1414
		$ids = array_unique($ids);
1415
 
1416
		$query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
1417
		if (count($ids) > 1) {
1418
			$query = str_replace('= (', 'IN (', $query);
1419
		}
1420
 
1421
		return $this->fetchAll($query, $Model->cacheQueries);
1422
	}
1423
 
1424
/**
1425
 * Fetch 'hasAndBelongsToMany' associations.
1426
 *
1427
 * @param Model $Model Primary model object.
1428
 * @param string $query Association query.
1429
 * @param array $ids Array of IDs of associated records.
1430
 * @param string $association Association name.
1431
 * @return array Association results.
1432
 */
1433
	protected function _fetchHasAndBelongsToMany(Model $Model, $query, $ids, $association) {
1434
		$ids = array_unique($ids);
1435
 
1436
		if (count($ids) > 1) {
1437
			$query = str_replace('{$__cakeID__$}', '(' . implode(', ', $ids) . ')', $query);
1438
			$query = str_replace('= (', 'IN (', $query);
1439
		} else {
1440
			$query = str_replace('{$__cakeID__$}', $ids[0], $query);
1441
		}
1442
		$query = str_replace(' WHERE 1 = 1', '', $query);
1443
 
1444
		return $this->fetchAll($query, $Model->cacheQueries);
1445
	}
1446
 
1447
/**
1448
 * Merge the results of 'hasMany' associations.
1449
 *
1450
 * Note: this function also deals with the formatting of the data.
1451
 *
1452
 * @param array &$resultSet Data to merge into.
1453
 * @param array $assocResultSet Data to merge.
1454
 * @param string $association Name of Model being merged.
1455
 * @param Model $Model Model being merged onto.
1456
 * @return void
1457
 */
1458
	protected function _mergeHasMany(&$resultSet, $assocResultSet, $association, Model $Model) {
1459
		$modelAlias = $Model->alias;
1460
		$primaryKey = $Model->primaryKey;
1461
		$foreignKey = $Model->hasMany[$association]['foreignKey'];
1462
 
1463
		foreach ($resultSet as &$result) {
1464
			if (!isset($result[$modelAlias])) {
1465
				continue;
1466
			}
1467
 
1468
			$resultPrimaryKey = $result[$modelAlias][$primaryKey];
1469
 
1470
			$merged = array();
1471
			foreach ($assocResultSet as $data) {
1472
				if ($resultPrimaryKey !== $data[$association][$foreignKey]) {
1473
					continue;
1474
				}
1475
 
1476
				if (count($data) > 1) {
1477
					$data = array_merge($data[$association], $data);
1478
					unset($data[$association]);
1479
					foreach ($data as $key => $name) {
1480
						if (is_numeric($key)) {
1481
							$data[$association][] = $name;
1482
							unset($data[$key]);
1483
						}
1484
					}
1485
					$merged[] = $data;
1486
				} else {
1487
					$merged[] = $data[$association];
1488
				}
1489
			}
1490
 
1491
			$result = Hash::mergeDiff($result, array($association => $merged));
1492
		}
1493
	}
1494
 
1495
/**
1496
 * Merge association of merge into data
1497
 *
1498
 * @param array &$data The data to merge.
1499
 * @param array &$merge The data to merge.
1500
 * @param string $association The association name to merge.
1501
 * @param string $type The type of association
1502
 * @param bool $selfJoin Whether or not this is a self join.
1503
 * @return void
1504
 */
1505
	protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
1506
		if (isset($merge[0]) && !isset($merge[0][$association])) {
1507
			$association = Inflector::pluralize($association);
1508
		}
1509
 
1510
		$dataAssociation =& $data[$association];
1511
 
1512
		if ($type === 'belongsTo' || $type === 'hasOne') {
1513
			if (isset($merge[$association])) {
1514
				$dataAssociation = $merge[$association][0];
1515
			} else {
1516
				if (!empty($merge[0][$association])) {
1517
					foreach ($merge[0] as $assoc => $data2) {
1518
						if ($assoc !== $association) {
1519
							$merge[0][$association][$assoc] = $data2;
1520
						}
1521
					}
1522
				}
1523
				if (!isset($dataAssociation)) {
1524
					$dataAssociation = array();
1525
					if ($merge[0][$association]) {
1526
						$dataAssociation = $merge[0][$association];
1527
					}
1528
				} else {
1529
					if (is_array($merge[0][$association])) {
1530
						foreach ($dataAssociation as $k => $v) {
1531
							if (!is_array($v)) {
1532
								$dataAssocTmp[$k] = $v;
1533
							}
1534
						}
1535
 
1536
						foreach ($merge[0][$association] as $k => $v) {
1537
							if (!is_array($v)) {
1538
								$mergeAssocTmp[$k] = $v;
1539
							}
1540
						}
1541
						$dataKeys = array_keys($data);
1542
						$mergeKeys = array_keys($merge[0]);
1543
 
1544
						if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
1545
							$dataAssociation[$association] = $merge[0][$association];
1546
						} else {
1547
							$diff = Hash::diff($dataAssocTmp, $mergeAssocTmp);
1548
							$dataAssociation = array_merge($merge[0][$association], $diff);
1549
						}
1550
					} elseif ($selfJoin && array_key_exists($association, $merge[0])) {
1551
						$dataAssociation = array_merge($dataAssociation, array($association => array()));
1552
					}
1553
				}
1554
			}
1555
		} else {
1556
			if (isset($merge[0][$association]) && $merge[0][$association] === false) {
1557
				if (!isset($dataAssociation)) {
1558
					$dataAssociation = array();
1559
				}
1560
			} else {
1561
				foreach ($merge as $row) {
1562
					$insert = array();
1563
					if (count($row) === 1) {
1564
						$insert = $row[$association];
1565
					} elseif (isset($row[$association])) {
1566
						$insert = array_merge($row[$association], $row);
1567
						unset($insert[$association]);
1568
					}
1569
 
1570
					if (empty($dataAssociation) || (isset($dataAssociation) && !in_array($insert, $dataAssociation, true))) {
1571
						$dataAssociation[] = $insert;
1572
					}
1573
				}
1574
			}
1575
		}
1576
	}
1577
 
1578
/**
1579
 * Prepares fields required by an SQL statement.
1580
 *
1581
 * When no fields are set, all the $Model fields are returned.
1582
 *
1583
 * @param Model $Model The model to prepare.
1584
 * @param array $queryData An array of queryData information containing keys similar to Model::find().
1585
 * @return array Array containing SQL fields.
1586
 */
1587
	public function prepareFields(Model $Model, $queryData) {
1588
		if (empty($queryData['fields'])) {
1589
			$queryData['fields'] = $this->fields($Model);
1590
 
1591
		} elseif (!empty($Model->hasMany) && $Model->recursive > -1) {
1592
			// hasMany relationships need the $Model primary key.
1593
			$assocFields = $this->fields($Model, null, "{$Model->alias}.{$Model->primaryKey}");
1594
			$passedFields = $queryData['fields'];
1595
 
1596
			if (
1597
				count($passedFields) > 1 ||
1598
				(strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0]))
1599
			) {
1600
				$queryData['fields'] = array_merge($passedFields, $assocFields);
1601
			}
1602
		}
1603
 
1604
		return array_unique($queryData['fields']);
1605
	}
1606
 
1607
/**
1608
 * Builds an SQL statement.
1609
 *
1610
 * This is merely a convenient wrapper to DboSource::buildStatement().
1611
 *
1612
 * @param Model $Model The model to build an association query for.
1613
 * @param array $queryData An array of queryData information containing keys similar to Model::find().
1614
 * @return string String containing an SQL statement.
1615
 * @see DboSource::buildStatement()
1616
 */
1617
	public function buildAssociationQuery(Model $Model, $queryData) {
1618
		$queryData = $this->_scrubQueryData($queryData);
1619
 
1620
		return $this->buildStatement(
1621
			array(
1622
				'fields' => $this->prepareFields($Model, $queryData),
1623
				'table' => $this->fullTableName($Model),
1624
				'alias' => $Model->alias,
1625
				'limit' => $queryData['limit'],
1626
				'offset' => $queryData['offset'],
1627
				'joins' => $queryData['joins'],
1628
				'conditions' => $queryData['conditions'],
1629
				'order' => $queryData['order'],
1630
				'group' => $queryData['group']
1631
			),
1632
			$Model
1633
		);
1634
	}
1635
 
1636
/**
1637
 * Generates a query or part of a query from a single model or two associated models.
1638
 *
1639
 * Builds a string containing an SQL statement template.
1640
 *
1641
 * @param Model $Model Primary Model object.
1642
 * @param Model|null $LinkModel Linked model object.
1643
 * @param string $type Association type, one of the model association types ie. hasMany.
1644
 * @param string $association Association name.
1645
 * @param array $assocData Association data.
1646
 * @param array &$queryData An array of queryData information containing keys similar to Model::find().
1647
 * @param bool $external Whether or not the association query is on an external datasource.
1648
 * @return mixed
1649
 *   String representing a query.
1650
 *   True, when $external is false and association $type is 'hasOne' or 'belongsTo'.
1651
 */
1652
	public function generateAssociationQuery(Model $Model, $LinkModel, $type, $association, $assocData, &$queryData, $external) {
1653
		$assocData = $this->_scrubQueryData($assocData);
1654
		$queryData = $this->_scrubQueryData($queryData);
1655
 
1656
		if ($LinkModel === null) {
1657
			return $this->buildStatement(
1658
				array(
1659
					'fields' => array_unique($queryData['fields']),
1660
					'table' => $this->fullTableName($Model),
1661
					'alias' => $Model->alias,
1662
					'limit' => $queryData['limit'],
1663
					'offset' => $queryData['offset'],
1664
					'joins' => $queryData['joins'],
1665
					'conditions' => $queryData['conditions'],
1666
					'order' => $queryData['order'],
1667
					'group' => $queryData['group']
1668
				),
1669
				$Model
1670
			);
1671
		}
1672
 
1673
		if ($external && !empty($assocData['finderQuery'])) {
1674
			return $assocData['finderQuery'];
1675
		}
1676
 
1677
		if ($type === 'hasMany' || $type === 'hasAndBelongsToMany') {
1678
			if (empty($assocData['offset']) && !empty($assocData['page'])) {
1679
				$assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
1680
			}
1681
		}
1682
 
1683
		switch ($type) {
1684
			case 'hasOne':
1685
			case 'belongsTo':
1686
				$conditions = $this->_mergeConditions(
1687
					$assocData['conditions'],
1688
					$this->getConstraint($type, $Model, $LinkModel, $association, array_merge($assocData, compact('external')))
1689
				);
1690
 
1691
				if ($external) {
1692
					// Not self join
1693
					if ($Model->name !== $LinkModel->name) {
1694
						$modelAlias = $Model->alias;
1695
						foreach ($conditions as $key => $condition) {
1696
							if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
1697
								unset($conditions[$key]);
1698
							}
1699
						}
1700
					}
1701
 
1702
					$query = array_merge($assocData, array(
1703
						'conditions' => $conditions,
1704
						'table' => $this->fullTableName($LinkModel),
1705
						'fields' => $this->fields($LinkModel, $association, $assocData['fields']),
1706
						'alias' => $association,
1707
						'group' => null
1708
					));
1709
				} else {
1710
					$join = array(
1711
						'table' => $LinkModel,
1712
						'alias' => $association,
1713
						'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
1714
						'conditions' => trim($this->conditions($conditions, true, false, $Model))
1715
					);
1716
 
1717
					$fields = array();
1718
					if ($assocData['fields'] !== false) {
1719
						$fields = $this->fields($LinkModel, $association, $assocData['fields']);
1720
					}
1721
 
1722
					$queryData['fields'] = array_merge($this->prepareFields($Model, $queryData), $fields);
1723
 
1724
					if (!empty($assocData['order'])) {
1725
						$queryData['order'][] = $assocData['order'];
1726
					}
1727
					if (!in_array($join, $queryData['joins'], true)) {
1728
						$queryData['joins'][] = $join;
1729
					}
1730
 
1731
					return true;
1732
				}
1733
				break;
1734
			case 'hasMany':
1735
				$assocData['fields'] = $this->fields($LinkModel, $association, $assocData['fields']);
1736
				if (!empty($assocData['foreignKey'])) {
1737
					$assocData['fields'] = array_merge($assocData['fields'], $this->fields($LinkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
1738
				}
1739
 
1740
				$query = array(
1741
					'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $Model, $LinkModel, $association, $assocData), $assocData['conditions']),
1742
					'fields' => array_unique($assocData['fields']),
1743
					'table' => $this->fullTableName($LinkModel),
1744
					'alias' => $association,
1745
					'order' => $assocData['order'],
1746
					'limit' => $assocData['limit'],
1747
					'offset' => $assocData['offset'],
1748
					'group' => null
1749
				);
1750
				break;
1751
			case 'hasAndBelongsToMany':
1752
				$joinFields = array();
1753
				$joinAssoc = null;
1754
 
1755
				if (isset($assocData['with']) && !empty($assocData['with'])) {
1756
					$joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
1757
					list($with, $joinFields) = $Model->joinModel($assocData['with'], $joinKeys);
1758
 
1759
					$joinTbl = $Model->{$with};
1760
					$joinAlias = $joinTbl;
1761
 
1762
					if (is_array($joinFields) && !empty($joinFields)) {
1763
						$joinAssoc = $joinAlias = $joinTbl->alias;
1764
						$joinFields = $this->fields($joinTbl, $joinAlias, $joinFields);
1765
					} else {
1766
						$joinFields = array();
1767
					}
1768
				} else {
1769
					$joinTbl = $assocData['joinTable'];
1770
					$joinAlias = $this->fullTableName($assocData['joinTable']);
1771
				}
1772
 
1773
				$query = array(
1774
					'conditions' => $assocData['conditions'],
1775
					'limit' => $assocData['limit'],
1776
					'offset' => $assocData['offset'],
1777
					'table' => $this->fullTableName($LinkModel),
1778
					'alias' => $association,
1779
					'fields' => array_merge($this->fields($LinkModel, $association, $assocData['fields']), $joinFields),
1780
					'order' => $assocData['order'],
1781
					'group' => null,
1782
					'joins' => array(array(
1783
						'table' => $joinTbl,
1784
						'alias' => $joinAssoc,
1785
						'conditions' => $this->getConstraint('hasAndBelongsToMany', $Model, $LinkModel, $joinAlias, $assocData, $association)
1786
					))
1787
				);
1788
				break;
1789
		}
1790
 
1791
		if (isset($query)) {
1792
			return $this->buildStatement($query, $Model);
1793
		}
1794
 
1795
		return null;
1796
	}
1797
 
1798
/**
1799
 * Returns a conditions array for the constraint between two models.
1800
 *
1801
 * @param string $type Association type.
1802
 * @param Model $Model Primary Model object.
1803
 * @param Model $LinkModel Linked model object.
1804
 * @param string $association Association name.
1805
 * @param array $assocData Association data.
1806
 * @param string $association2 HABTM association name.
1807
 * @return array Conditions array defining the constraint between $Model and $LinkModel.
1808
 */
1809
	public function getConstraint($type, Model $Model, Model $LinkModel, $association, $assocData, $association2 = null) {
1810
		$assocData += array('external' => false);
1811
 
1812
		if (empty($assocData['foreignKey'])) {
1813
			return array();
1814
		}
1815
 
1816
		switch ($type) {
1817
			case 'hasOne':
1818
				if ($assocData['external']) {
1819
					return array(
1820
						"{$association}.{$assocData['foreignKey']}" => '{$__cakeID__$}'
1821
					);
1822
				} else {
1823
					return array(
1824
						"{$association}.{$assocData['foreignKey']}" => $this->identifier("{$Model->alias}.{$Model->primaryKey}")
1825
					);
1826
				}
1827
			case 'belongsTo':
1828
				if ($assocData['external']) {
1829
					return array(
1830
						"{$association}.{$LinkModel->primaryKey}" => '{$__cakeForeignKey__$}'
1831
					);
1832
				} else {
1833
					return array(
1834
						"{$Model->alias}.{$assocData['foreignKey']}" => $this->identifier("{$association}.{$LinkModel->primaryKey}")
1835
					);
1836
				}
1837
			case 'hasMany':
1838
				return array("{$association}.{$assocData['foreignKey']}" => array('{$__cakeID__$}'));
1839
			case 'hasAndBelongsToMany':
1840
				return array(
1841
					array(
1842
						"{$association}.{$assocData['foreignKey']}" => '{$__cakeID__$}'
1843
					),
1844
					array(
1845
						"{$association}.{$assocData['associationForeignKey']}" => $this->identifier("{$association2}.{$LinkModel->primaryKey}")
1846
					)
1847
				);
1848
		}
1849
 
1850
		return array();
1851
	}
1852
 
1853
/**
1854
 * Builds and generates a JOIN condition from an array. Handles final clean-up before conversion.
1855
 *
1856
 * @param array $join An array defining a JOIN condition in a query.
1857
 * @return string An SQL JOIN condition to be used in a query.
1858
 * @see DboSource::renderJoinStatement()
1859
 * @see DboSource::buildStatement()
1860
 */
1861
	public function buildJoinStatement($join) {
1862
		$data = array_merge(array(
1863
			'type' => null,
1864
			'alias' => null,
1865
			'table' => 'join_table',
1866
			'conditions' => array()
1867
		), $join);
1868
 
1869
		if (!empty($data['alias'])) {
1870
			$data['alias'] = $this->alias . $this->name($data['alias']);
1871
		}
1872
		if (!empty($data['conditions'])) {
1873
			$data['conditions'] = trim($this->conditions($data['conditions'], true, false));
1874
		}
1875
		if (!empty($data['table']) && (!is_string($data['table']) || strpos($data['table'], '(') !== 0)) {
1876
			$data['table'] = $this->fullTableName($data['table']);
1877
		}
1878
		return $this->renderJoinStatement($data);
1879
	}
1880
 
1881
/**
1882
 * Builds and generates an SQL statement from an array. Handles final clean-up before conversion.
1883
 *
1884
 * @param array $query An array defining an SQL query.
1885
 * @param Model $Model The model object which initiated the query.
1886
 * @return string An executable SQL statement.
1887
 * @see DboSource::renderStatement()
1888
 */
1889
	public function buildStatement($query, Model $Model) {
1890
		$query = array_merge($this->_queryDefaults, $query);
1891
 
1892
		if (!empty($query['joins'])) {
1893
			$count = count($query['joins']);
1894
			for ($i = 0; $i < $count; $i++) {
1895
				if (is_array($query['joins'][$i])) {
1896
					$query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
1897
				}
1898
			}
1899
		}
1900
 
1901
		return $this->renderStatement('select', array(
1902
			'conditions' => $this->conditions($query['conditions'], true, true, $Model),
1903
			'fields' => implode(', ', $query['fields']),
1904
			'table' => $query['table'],
1905
			'alias' => $this->alias . $this->name($query['alias']),
1906
			'order' => $this->order($query['order'], 'ASC', $Model),
1907
			'limit' => $this->limit($query['limit'], $query['offset']),
1908
			'joins' => implode(' ', $query['joins']),
1909
			'group' => $this->group($query['group'], $Model)
1910
		));
1911
	}
1912
 
1913
/**
1914
 * Renders a final SQL JOIN statement
1915
 *
1916
 * @param array $data The data to generate a join statement for.
1917
 * @return string
1918
 */
1919
	public function renderJoinStatement($data) {
1920
		if (strtoupper($data['type']) === 'CROSS') {
1921
			return "{$data['type']} JOIN {$data['table']} {$data['alias']}";
1922
		}
1923
		return trim("{$data['type']} JOIN {$data['table']} {$data['alias']} ON ({$data['conditions']})");
1924
	}
1925
 
1926
/**
1927
 * Renders a final SQL statement by putting together the component parts in the correct order
1928
 *
1929
 * @param string $type type of query being run. e.g select, create, update, delete, schema, alter.
1930
 * @param array $data Array of data to insert into the query.
1931
 * @return string Rendered SQL expression to be run.
1932
 */
1933
	public function renderStatement($type, $data) {
1934
		extract($data);
1935
		$aliases = null;
1936
 
1937
		switch (strtolower($type)) {
1938
			case 'select':
1939
				return trim("SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}");
1940
			case 'create':
1941
				return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
1942
			case 'update':
1943
				if (!empty($alias)) {
1944
					$aliases = "{$this->alias}{$alias} {$joins} ";
1945
				}
1946
				return trim("UPDATE {$table} {$aliases}SET {$fields} {$conditions}");
1947
			case 'delete':
1948
				if (!empty($alias)) {
1949
					$aliases = "{$this->alias}{$alias} {$joins} ";
1950
				}
1951
				return trim("DELETE {$alias} FROM {$table} {$aliases}{$conditions}");
1952
			case 'schema':
1953
				foreach (array('columns', 'indexes', 'tableParameters') as $var) {
1954
					if (is_array(${$var})) {
1955
						${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
1956
					} else {
1957
						${$var} = '';
1958
					}
1959
				}
1960
				if (trim($indexes) !== '') {
1961
					$columns .= ',';
1962
				}
1963
				return "CREATE TABLE {$table} (\n{$columns}{$indexes}) {$tableParameters};";
1964
			case 'alter':
1965
				return;
1966
		}
1967
	}
1968
 
1969
/**
1970
 * Merges a mixed set of string/array conditions.
1971
 *
1972
 * @param mixed $query The query to merge conditions for.
1973
 * @param mixed $assoc The association names.
1974
 * @return array
1975
 */
1976
	protected function _mergeConditions($query, $assoc) {
1977
		if (empty($assoc)) {
1978
			return $query;
1979
		}
1980
 
1981
		if (is_array($query)) {
1982
			return array_merge((array)$assoc, $query);
1983
		}
1984
 
1985
		if (!empty($query)) {
1986
			$query = array($query);
1987
			if (is_array($assoc)) {
1988
				$query = array_merge($query, $assoc);
1989
			} else {
1990
				$query[] = $assoc;
1991
			}
1992
			return $query;
1993
		}
1994
 
1995
		return $assoc;
1996
	}
1997
 
1998
/**
1999
 * Generates and executes an SQL UPDATE statement for given model, fields, and values.
2000
 * For databases that do not support aliases in UPDATE queries.
2001
 *
2002
 * @param Model $Model The model to update.
2003
 * @param array $fields The fields to update
2004
 * @param array $values The values fo the fields.
2005
 * @param mixed $conditions The conditions for the update. When non-empty $values will not be quoted.
2006
 * @return bool Success
2007
 */
2008
	public function update(Model $Model, $fields = array(), $values = null, $conditions = null) {
2009
		if (!$values) {
2010
			$combined = $fields;
2011
		} else {
2012
			$combined = array_combine($fields, $values);
2013
		}
2014
 
2015
		$fields = implode(', ', $this->_prepareUpdateFields($Model, $combined, empty($conditions)));
2016
 
2017
		$alias = $joins = null;
2018
		$table = $this->fullTableName($Model);
2019
		$conditions = $this->_matchRecords($Model, $conditions);
2020
 
2021
		if ($conditions === false) {
2022
			return false;
2023
		}
2024
		$query = compact('table', 'alias', 'joins', 'fields', 'conditions');
2025
 
2026
		if (!$this->execute($this->renderStatement('update', $query))) {
2027
			$Model->onError();
2028
			return false;
2029
		}
2030
		return true;
2031
	}
2032
 
2033
/**
2034
 * Quotes and prepares fields and values for an SQL UPDATE statement
2035
 *
2036
 * @param Model $Model The model to prepare fields for.
2037
 * @param array $fields The fields to update.
2038
 * @param bool $quoteValues If values should be quoted, or treated as SQL snippets
2039
 * @param bool $alias Include the model alias in the field name
2040
 * @return array Fields and values, quoted and prepared
2041
 */
2042
	protected function _prepareUpdateFields(Model $Model, $fields, $quoteValues = true, $alias = false) {
2043
		$quotedAlias = $this->startQuote . $Model->alias . $this->endQuote;
2044
 
2045
		$updates = array();
2046
		foreach ($fields as $field => $value) {
2047
			if ($alias && strpos($field, '.') === false) {
2048
				$quoted = $Model->escapeField($field);
2049
			} elseif (!$alias && strpos($field, '.') !== false) {
2050
				$quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
2051
					$Model->alias . '.', '', $field
2052
				)));
2053
			} else {
2054
				$quoted = $this->name($field);
2055
			}
2056
 
2057
			if ($value === null) {
2058
				$updates[] = $quoted . ' = NULL';
2059
				continue;
2060
			}
2061
			$update = $quoted . ' = ';
2062
 
2063
			if ($quoteValues) {
2064
				$update .= $this->value($value, $Model->getColumnType($field));
2065
			} elseif ($Model->getColumnType($field) === 'boolean' && (is_int($value) || is_bool($value))) {
2066
				$update .= $this->boolean($value, true);
2067
			} elseif (!$alias) {
2068
				$update .= str_replace($quotedAlias . '.', '', str_replace(
2069
					$Model->alias . '.', '', $value
2070
				));
2071
			} else {
2072
				$update .= $value;
2073
			}
2074
			$updates[] = $update;
2075
		}
2076
		return $updates;
2077
	}
2078
 
2079
/**
2080
 * Generates and executes an SQL DELETE statement.
2081
 * For databases that do not support aliases in UPDATE queries.
2082
 *
2083
 * @param Model $Model The model to delete from
2084
 * @param mixed $conditions The conditions to use. If empty the model's primary key will be used.
2085
 * @return bool Success
2086
 */
2087
	public function delete(Model $Model, $conditions = null) {
2088
		$alias = $joins = null;
2089
		$table = $this->fullTableName($Model);
2090
		$conditions = $this->_matchRecords($Model, $conditions);
2091
 
2092
		if ($conditions === false) {
2093
			return false;
2094
		}
2095
 
2096
		if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
2097
			$Model->onError();
2098
			return false;
2099
		}
2100
		return true;
2101
	}
2102
 
2103
/**
2104
 * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes
2105
 * in databases that do not support aliases in UPDATE/DELETE queries.
2106
 *
2107
 * @param Model $Model The model to find matching records for.
2108
 * @param mixed $conditions The conditions to match against.
2109
 * @return array List of record IDs
2110
 */
2111
	protected function _matchRecords(Model $Model, $conditions = null) {
2112
		if ($conditions === true) {
2113
			$conditions = $this->conditions(true);
2114
		} elseif ($conditions === null) {
2115
			$conditions = $this->conditions($this->defaultConditions($Model, $conditions, false), true, true, $Model);
2116
		} else {
2117
			$noJoin = true;
2118
			foreach ($conditions as $field => $value) {
2119
				$originalField = $field;
2120
				if (strpos($field, '.') !== false) {
2121
					list(, $field) = explode('.', $field);
2122
					$field = ltrim($field, $this->startQuote);
2123
					$field = rtrim($field, $this->endQuote);
2124
				}
2125
				if (!$Model->hasField($field)) {
2126
					$noJoin = false;
2127
					break;
2128
				}
2129
				if ($field !== $originalField) {
2130
					$conditions[$field] = $value;
2131
					unset($conditions[$originalField]);
2132
				}
2133
			}
2134
			if ($noJoin === true) {
2135
				return $this->conditions($conditions);
2136
			}
2137
			$idList = $Model->find('all', array(
2138
				'fields' => "{$Model->alias}.{$Model->primaryKey}",
2139
				'conditions' => $conditions
2140
			));
2141
 
2142
			if (empty($idList)) {
2143
				return false;
2144
			}
2145
 
2146
			$conditions = $this->conditions(array(
2147
				$Model->primaryKey => Hash::extract($idList, "{n}.{$Model->alias}.{$Model->primaryKey}")
2148
			));
2149
		}
2150
 
2151
		return $conditions;
2152
	}
2153
 
2154
/**
2155
 * Returns an array of SQL JOIN conditions from a model's associations.
2156
 *
2157
 * @param Model $Model The model to get joins for.2
2158
 * @return array
2159
 */
2160
	protected function _getJoins(Model $Model) {
2161
		$join = array();
2162
		$joins = array_merge($Model->getAssociated('hasOne'), $Model->getAssociated('belongsTo'));
2163
 
2164
		foreach ($joins as $assoc) {
2165
			if (!isset($Model->{$assoc})) {
2166
				continue;
2167
			}
2168
 
2169
			$LinkModel = $Model->{$assoc};
2170
 
2171
			if ($Model->useDbConfig !== $LinkModel->useDbConfig) {
2172
				continue;
2173
			}
2174
 
2175
			$assocData = $Model->getAssociated($assoc);
2176
 
2177
			$join[] = $this->buildJoinStatement(array(
2178
				'table' => $LinkModel,
2179
				'alias' => $assoc,
2180
				'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
2181
				'conditions' => trim($this->conditions(
2182
					$this->_mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $Model, $LinkModel, $assoc, $assocData)),
2183
					true,
2184
					false,
2185
					$Model
2186
				))
2187
			));
2188
		}
2189
 
2190
		return $join;
2191
	}
2192
 
2193
/**
2194
 * Returns an SQL calculation, i.e. COUNT() or MAX()
2195
 *
2196
 * @param Model $Model The model to get a calculated field for.
2197
 * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
2198
 * @param array $params Function parameters (any values must be quoted manually)
2199
 * @return string An SQL calculation function
2200
 */
2201
	public function calculate(Model $Model, $func, $params = array()) {
2202
		$params = (array)$params;
2203
 
2204
		switch (strtolower($func)) {
2205
			case 'count':
2206
				if (!isset($params[0])) {
2207
					$params[0] = '*';
2208
				}
2209
				if (!isset($params[1])) {
2210
					$params[1] = 'count';
2211
				}
2212
				if ($Model->isVirtualField($params[0])) {
2213
					$arg = $this->_quoteFields($Model->getVirtualField($params[0]));
2214
				} else {
2215
					$arg = $this->name($params[0]);
2216
				}
2217
				return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]);
2218
			case 'max':
2219
			case 'min':
2220
				if (!isset($params[1])) {
2221
					$params[1] = $params[0];
2222
				}
2223
				if ($Model->isVirtualField($params[0])) {
2224
					$arg = $this->_quoteFields($Model->getVirtualField($params[0]));
2225
				} else {
2226
					$arg = $this->name($params[0]);
2227
				}
2228
				return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]);
2229
		}
2230
	}
2231
 
2232
/**
2233
 * Deletes all the records in a table and resets the count of the auto-incrementing
2234
 * primary key, where applicable.
2235
 *
2236
 * @param Model|string $table A string or model class representing the table to be truncated
2237
 * @return bool SQL TRUNCATE TABLE statement, false if not applicable.
2238
 */
2239
	public function truncate($table) {
2240
		return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
2241
	}
2242
 
2243
/**
2244
 * Check if the server support nested transactions
2245
 *
2246
 * @return bool
2247
 */
2248
	public function nestedTransactionSupported() {
2249
		return false;
2250
	}
2251
 
2252
/**
2253
 * Begin a transaction
2254
 *
2255
 * @return bool True on success, false on fail
2256
 * (i.e. if the database/model does not support transactions,
2257
 * or a transaction has not started).
2258
 */
2259
	public function begin() {
2260
		if ($this->_transactionStarted) {
2261
			if ($this->nestedTransactionSupported()) {
2262
				return $this->_beginNested();
2263
			}
2264
			$this->_transactionNesting++;
2265
			return $this->_transactionStarted;
2266
		}
2267
 
2268
		$this->_transactionNesting = 0;
2269
		if ($this->fullDebug) {
2270
			$this->logQuery('BEGIN');
2271
		}
2272
		return $this->_transactionStarted = $this->_connection->beginTransaction();
2273
	}
2274
 
2275
/**
2276
 * Begin a nested transaction
2277
 *
2278
 * @return bool
2279
 */
2280
	protected function _beginNested() {
2281
		$query = 'SAVEPOINT LEVEL' . ++$this->_transactionNesting;
2282
		if ($this->fullDebug) {
2283
			$this->logQuery($query);
2284
		}
2285
		$this->_connection->exec($query);
2286
		return true;
2287
	}
2288
 
2289
/**
2290
 * Commit a transaction
2291
 *
2292
 * @return bool True on success, false on fail
2293
 * (i.e. if the database/model does not support transactions,
2294
 * or a transaction has not started).
2295
 */
2296
	public function commit() {
2297
		if (!$this->_transactionStarted) {
2298
			return false;
2299
		}
2300
 
2301
		if ($this->_transactionNesting === 0) {
2302
			if ($this->fullDebug) {
2303
				$this->logQuery('COMMIT');
2304
			}
2305
			$this->_transactionStarted = false;
2306
			return $this->_connection->commit();
2307
		}
2308
 
2309
		if ($this->nestedTransactionSupported()) {
2310
			return $this->_commitNested();
2311
		}
2312
 
2313
		$this->_transactionNesting--;
2314
		return true;
2315
	}
2316
 
2317
/**
2318
 * Commit a nested transaction
2319
 *
2320
 * @return bool
2321
 */
2322
	protected function _commitNested() {
2323
		$query = 'RELEASE SAVEPOINT LEVEL' . $this->_transactionNesting--;
2324
		if ($this->fullDebug) {
2325
			$this->logQuery($query);
2326
		}
2327
		$this->_connection->exec($query);
2328
		return true;
2329
	}
2330
 
2331
/**
2332
 * Rollback a transaction
2333
 *
2334
 * @return bool True on success, false on fail
2335
 * (i.e. if the database/model does not support transactions,
2336
 * or a transaction has not started).
2337
 */
2338
	public function rollback() {
2339
		if (!$this->_transactionStarted) {
2340
			return false;
2341
		}
2342
 
2343
		if ($this->_transactionNesting === 0) {
2344
			if ($this->fullDebug) {
2345
				$this->logQuery('ROLLBACK');
2346
			}
2347
			$this->_transactionStarted = false;
2348
			return $this->_connection->rollBack();
2349
		}
2350
 
2351
		if ($this->nestedTransactionSupported()) {
2352
			return $this->_rollbackNested();
2353
		}
2354
 
2355
		$this->_transactionNesting--;
2356
		return true;
2357
	}
2358
 
2359
/**
2360
 * Rollback a nested transaction
2361
 *
2362
 * @return bool
2363
 */
2364
	protected function _rollbackNested() {
2365
		$query = 'ROLLBACK TO SAVEPOINT LEVEL' . $this->_transactionNesting--;
2366
		if ($this->fullDebug) {
2367
			$this->logQuery($query);
2368
		}
2369
		$this->_connection->exec($query);
2370
		return true;
2371
	}
2372
 
2373
/**
2374
 * Returns the ID generated from the previous INSERT operation.
2375
 *
2376
 * @param mixed $source The source to get an id for.
2377
 * @return mixed
2378
 */
2379
	public function lastInsertId($source = null) {
2380
		return $this->_connection->lastInsertId();
2381
	}
2382
 
2383
/**
2384
 * Creates a default set of conditions from the model if $conditions is null/empty.
2385
 * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions
2386
 * were provided either null or false will be returned based on what was input.
2387
 *
2388
 * @param Model $Model The model to get conditions for.
2389
 * @param string|array|bool $conditions Array of conditions, conditions string, null or false. If an array of conditions,
2390
 *   or string conditions those conditions will be returned. With other values the model's existence will be checked.
2391
 *   If the model doesn't exist a null or false will be returned depending on the input value.
2392
 * @param bool $useAlias Use model aliases rather than table names when generating conditions
2393
 * @return mixed Either null, false, $conditions or an array of default conditions to use.
2394
 * @see DboSource::update()
2395
 * @see DboSource::conditions()
2396
 */
2397
	public function defaultConditions(Model $Model, $conditions, $useAlias = true) {
2398
		if (!empty($conditions)) {
2399
			return $conditions;
2400
		}
2401
		$exists = $Model->exists();
2402
		if (!$exists && ($conditions !== null || !empty($Model->__safeUpdateMode))) {
2403
			return false;
2404
		} elseif (!$exists) {
2405
			return null;
2406
		}
2407
		$alias = $Model->alias;
2408
 
2409
		if (!$useAlias) {
2410
			$alias = $this->fullTableName($Model, false);
2411
		}
2412
		return array("{$alias}.{$Model->primaryKey}" => $Model->getID());
2413
	}
2414
 
2415
/**
2416
 * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
2417
 *
2418
 * @param Model $Model The model to get a key for.
2419
 * @param string $key The key field.
2420
 * @param string $assoc The association name.
2421
 * @return string
2422
 */
2423
	public function resolveKey(Model $Model, $key, $assoc = null) {
2424
		if (strpos('.', $key) !== false) {
2425
			return $this->name($Model->alias) . '.' . $this->name($key);
2426
		}
2427
		return $key;
2428
	}
2429
 
2430
/**
2431
 * Private helper method to remove query metadata in given data array.
2432
 *
2433
 * @param array $data The data to scrub.
2434
 * @return array
2435
 */
2436
	protected function _scrubQueryData($data) {
2437
		static $base = null;
2438
		if ($base === null) {
2439
			$base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
2440
			$base['callbacks'] = null;
2441
		}
2442
		return (array)$data + $base;
2443
	}
2444
 
2445
/**
2446
 * Converts model virtual fields into sql expressions to be fetched later
2447
 *
2448
 * @param Model $Model The model to get virtual fields for.
2449
 * @param string $alias Alias table name
2450
 * @param array $fields virtual fields to be used on query
2451
 * @return array
2452
 */
2453
	protected function _constructVirtualFields(Model $Model, $alias, $fields) {
2454
		$virtual = array();
2455
		foreach ($fields as $field) {
2456
			$virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
2457
			$expression = $this->_quoteFields($Model->getVirtualField($field));
2458
			$virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}";
2459
		}
2460
		return $virtual;
2461
	}
2462
 
2463
/**
2464
 * Generates the fields list of an SQL query.
2465
 *
2466
 * @param Model $Model The model to get fields for.
2467
 * @param string $alias Alias table name
2468
 * @param mixed $fields The provided list of fields.
2469
 * @param bool $quote If false, returns fields array unquoted
2470
 * @return array
2471
 */
2472
	public function fields(Model $Model, $alias = null, $fields = array(), $quote = true) {
2473
		if (empty($alias)) {
2474
			$alias = $Model->alias;
2475
		}
2476
		$virtualFields = $Model->getVirtualField();
2477
		$cacheKey = array(
2478
			$alias,
2479
			get_class($Model),
2480
			$Model->alias,
2481
			$virtualFields,
2482
			$fields,
2483
			$quote,
2484
			ConnectionManager::getSourceName($this),
2485
			$Model->schemaName,
2486
			$Model->table
2487
		);
2488
		$cacheKey = md5(serialize($cacheKey));
2489
		if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
2490
			return $return;
2491
		}
2492
		$allFields = empty($fields);
2493
		if ($allFields) {
2494
			$fields = array_keys($Model->schema());
2495
		} elseif (!is_array($fields)) {
2496
			$fields = String::tokenize($fields);
2497
		}
2498
		$fields = array_values(array_filter($fields));
2499
		$allFields = $allFields || in_array('*', $fields) || in_array($Model->alias . '.*', $fields);
2500
 
2501
		$virtual = array();
2502
		if (!empty($virtualFields)) {
2503
			$virtualKeys = array_keys($virtualFields);
2504
			foreach ($virtualKeys as $field) {
2505
				$virtualKeys[] = $Model->alias . '.' . $field;
2506
			}
2507
			$virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields);
2508
			foreach ($virtual as $i => $field) {
2509
				if (strpos($field, '.') !== false) {
2510
					$virtual[$i] = str_replace($Model->alias . '.', '', $field);
2511
				}
2512
				$fields = array_diff($fields, array($field));
2513
			}
2514
			$fields = array_values($fields);
2515
		}
2516
		if (!$quote) {
2517
			if (!empty($virtual)) {
2518
				$fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual));
2519
			}
2520
			return $fields;
2521
		}
2522
		$count = count($fields);
2523
 
2524
		if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
2525
			for ($i = 0; $i < $count; $i++) {
2526
				if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) {
2527
					unset($fields[$i]);
2528
					continue;
2529
				}
2530
				if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') {
2531
					$fields[$i] = $fields[$i]->value;
2532
				} elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])) {
2533
					continue;
2534
				} elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
2535
					$prepend = '';
2536
 
2537
					if (strpos($fields[$i], 'DISTINCT') !== false) {
2538
						$prepend = 'DISTINCT ';
2539
						$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
2540
					}
2541
					$dot = strpos($fields[$i], '.');
2542
 
2543
					if ($dot === false) {
2544
						$prefix = !(
2545
							strpos($fields[$i], ' ') !== false ||
2546
							strpos($fields[$i], '(') !== false
2547
						);
2548
						$fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]);
2549
					} else {
2550
						if (strpos($fields[$i], ',') === false) {
2551
							$build = explode('.', $fields[$i]);
2552
							if (!Hash::numeric($build)) {
2553
								$fields[$i] = $this->name(implode('.', $build));
2554
							}
2555
						}
2556
					}
2557
					$fields[$i] = $prepend . $fields[$i];
2558
				} elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
2559
					if (isset($field[1])) {
2560
						if (strpos($field[1], '.') === false) {
2561
							$field[1] = $this->name($alias . '.' . $field[1]);
2562
						} else {
2563
							$field[0] = explode('.', $field[1]);
2564
							if (!Hash::numeric($field[0])) {
2565
								$field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
2566
								$fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
2567
							}
2568
						}
2569
					}
2570
				}
2571
			}
2572
		}
2573
		if (!empty($virtual)) {
2574
			$fields = array_merge($fields, $this->_constructVirtualFields($Model, $alias, $virtual));
2575
		}
2576
		return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields));
2577
	}
2578
 
2579
/**
2580
 * Creates a WHERE clause by parsing given conditions data. If an array or string
2581
 * conditions are provided those conditions will be parsed and quoted. If a boolean
2582
 * is given it will be integer cast as condition. Null will return 1 = 1.
2583
 *
2584
 * Results of this method are stored in a memory cache. This improves performance, but
2585
 * because the method uses a hashing algorithm it can have collisions.
2586
 * Setting DboSource::$cacheMethods to false will disable the memory cache.
2587
 *
2588
 * @param mixed $conditions Array or string of conditions, or any value.
2589
 * @param bool $quoteValues If true, values should be quoted
2590
 * @param bool $where If true, "WHERE " will be prepended to the return value
2591
 * @param Model $Model A reference to the Model instance making the query
2592
 * @return string SQL fragment
2593
 */
2594
	public function conditions($conditions, $quoteValues = true, $where = true, Model $Model = null) {
2595
		$clause = $out = '';
2596
 
2597
		if ($where) {
2598
			$clause = ' WHERE ';
2599
		}
2600
 
2601
		if (is_array($conditions) && !empty($conditions)) {
2602
			$out = $this->conditionKeysToString($conditions, $quoteValues, $Model);
2603
 
2604
			if (empty($out)) {
2605
				return $clause . ' 1 = 1';
2606
			}
2607
			return $clause . implode(' AND ', $out);
2608
		}
2609
 
2610
		if (is_bool($conditions)) {
2611
			return $clause . (int)$conditions . ' = 1';
2612
		}
2613
 
2614
		if (empty($conditions) || trim($conditions) === '') {
2615
			return $clause . '1 = 1';
2616
		}
2617
 
2618
		$clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
2619
 
2620
		if (preg_match($clauses, $conditions)) {
2621
			$clause = '';
2622
		}
2623
 
2624
		$conditions = $this->_quoteFields($conditions);
2625
 
2626
		return $clause . $conditions;
2627
	}
2628
 
2629
/**
2630
 * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions().
2631
 *
2632
 * @param array $conditions Array or string of conditions
2633
 * @param bool $quoteValues If true, values should be quoted
2634
 * @param Model $Model A reference to the Model instance making the query
2635
 * @return string SQL fragment
2636
 */
2637
	public function conditionKeysToString($conditions, $quoteValues = true, Model $Model = null) {
2638
		$out = array();
2639
		$data = $columnType = null;
2640
		$bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
2641
 
2642
		foreach ($conditions as $key => $value) {
2643
			$join = ' AND ';
2644
			$not = null;
2645
 
2646
			if (is_array($value)) {
2647
				$valueInsert = (
2648
					!empty($value) &&
2649
					(substr_count($key, '?') === count($value) || substr_count($key, ':') === count($value))
2650
				);
2651
			}
2652
 
2653
			if (is_numeric($key) && empty($value)) {
2654
				continue;
2655
			} elseif (is_numeric($key) && is_string($value)) {
2656
				$out[] = $this->_quoteFields($value);
2657
			} elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
2658
				if (in_array(strtolower(trim($key)), $bool)) {
2659
					$join = ' ' . strtoupper($key) . ' ';
2660
				} else {
2661
					$key = $join;
2662
				}
2663
				$value = $this->conditionKeysToString($value, $quoteValues, $Model);
2664
 
2665
				if (strpos($join, 'NOT') !== false) {
2666
					if (strtoupper(trim($key)) === 'NOT') {
2667
						$key = 'AND ' . trim($key);
2668
					}
2669
					$not = 'NOT ';
2670
				}
2671
 
2672
				if (empty($value)) {
2673
					continue;
2674
				}
2675
 
2676
				if (empty($value[1])) {
2677
					if ($not) {
2678
						$out[] = $not . '(' . $value[0] . ')';
2679
					} else {
2680
						$out[] = $value[0];
2681
					}
2682
				} else {
2683
					$out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))';
2684
				}
2685
			} else {
2686
				if (is_object($value) && isset($value->type)) {
2687
					if ($value->type === 'identifier') {
2688
						$data .= $this->name($key) . ' = ' . $this->name($value->value);
2689
					} elseif ($value->type === 'expression') {
2690
						if (is_numeric($key)) {
2691
							$data .= $value->value;
2692
						} else {
2693
							$data .= $this->name($key) . ' = ' . $value->value;
2694
						}
2695
					}
2696
				} elseif (is_array($value) && !empty($value) && !$valueInsert) {
2697
					$keys = array_keys($value);
2698
					if ($keys === array_values($keys)) {
2699
						$count = count($value);
2700
						if ($count === 1 && !preg_match('/\s+(?:NOT|\!=)$/', $key)) {
2701
							$data = $this->_quoteFields($key) . ' = (';
2702
							if ($quoteValues) {
2703
								if ($Model !== null) {
2704
									$columnType = $Model->getColumnType($key);
2705
								}
2706
								$data .= implode(', ', $this->value($value, $columnType));
2707
							}
2708
							$data .= ')';
2709
						} else {
2710
							$data = $this->_parseKey($key, $value, $Model);
2711
						}
2712
					} else {
2713
						$ret = $this->conditionKeysToString($value, $quoteValues, $Model);
2714
						if (count($ret) > 1) {
2715
							$data = '(' . implode(') AND (', $ret) . ')';
2716
						} elseif (isset($ret[0])) {
2717
							$data = $ret[0];
2718
						}
2719
					}
2720
				} elseif (is_numeric($key) && !empty($value)) {
2721
					$data = $this->_quoteFields($value);
2722
				} else {
2723
					$data = $this->_parseKey(trim($key), $value, $Model);
2724
				}
2725
 
2726
				if ($data) {
2727
					$out[] = $data;
2728
					$data = null;
2729
				}
2730
			}
2731
		}
2732
		return $out;
2733
	}
2734
 
2735
/**
2736
 * Extracts a Model.field identifier and an SQL condition operator from a string, formats
2737
 * and inserts values, and composes them into an SQL snippet.
2738
 *
2739
 * @param string $key An SQL key snippet containing a field and optional SQL operator
2740
 * @param mixed $value The value(s) to be inserted in the string
2741
 * @param Model $Model Model object initiating the query
2742
 * @return string
2743
 */
2744
	protected function _parseKey($key, $value, Model $Model = null) {
2745
		$operatorMatch = '/^(((' . implode(')|(', $this->_sqlOps);
2746
		$operatorMatch .= ')\\x20?)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
2747
		$bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
2748
 
2749
		if (strpos($key, ' ') === false) {
2750
			$operator = '=';
2751
		} else {
2752
			list($key, $operator) = explode(' ', trim($key), 2);
2753
 
2754
			if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
2755
				$key = $key . ' ' . $operator;
2756
				$split = strrpos($key, ' ');
2757
				$operator = substr($key, $split);
2758
				$key = substr($key, 0, $split);
2759
			}
2760
		}
2761
 
2762
		$virtual = false;
2763
		$type = null;
2764
 
2765
		if ($Model !== null) {
2766
			if ($Model->isVirtualField($key)) {
2767
				$key = $this->_quoteFields($Model->getVirtualField($key));
2768
				$virtual = true;
2769
			}
2770
 
2771
			$type = $Model->getColumnType($key);
2772
		}
2773
 
2774
		$null = $value === null || (is_array($value) && empty($value));
2775
 
2776
		if (strtolower($operator) === 'not') {
2777
			$data = $this->conditionKeysToString(
2778
				array($operator => array($key => $value)), true, $Model
2779
			);
2780
			return $data[0];
2781
		}
2782
 
2783
		$value = $this->value($value, $type);
2784
 
2785
		if (!$virtual && $key !== '?') {
2786
			$isKey = (
2787
				strpos($key, '(') !== false ||
2788
				strpos($key, ')') !== false ||
2789
				strpos($key, '|') !== false
2790
			);
2791
			$key = $isKey ? $this->_quoteFields($key) : $this->name($key);
2792
		}
2793
 
2794
		if ($bound) {
2795
			return String::insert($key . ' ' . trim($operator), $value);
2796
		}
2797
 
2798
		if (!preg_match($operatorMatch, trim($operator))) {
2799
			$operator .= is_array($value) ? ' IN' : ' =';
2800
		}
2801
		$operator = trim($operator);
2802
 
2803
		if (is_array($value)) {
2804
			$value = implode(', ', $value);
2805
 
2806
			switch ($operator) {
2807
				case '=':
2808
					$operator = 'IN';
2809
					break;
2810
				case '!=':
2811
				case '<>':
2812
					$operator = 'NOT IN';
2813
					break;
2814
			}
2815
			$value = "({$value})";
2816
		} elseif ($null || $value === 'NULL') {
2817
			switch ($operator) {
2818
				case '=':
2819
					$operator = 'IS';
2820
					break;
2821
				case '!=':
2822
				case '<>':
2823
					$operator = 'IS NOT';
2824
					break;
2825
			}
2826
		}
2827
		if ($virtual) {
2828
			return "({$key}) {$operator} {$value}";
2829
		}
2830
		return "{$key} {$operator} {$value}";
2831
	}
2832
 
2833
/**
2834
 * Quotes Model.fields
2835
 *
2836
 * @param string $conditions The conditions to quote.
2837
 * @return string or false if no match
2838
 */
2839
	protected function _quoteFields($conditions) {
2840
		$start = $end = null;
2841
		$original = $conditions;
2842
 
2843
		if (!empty($this->startQuote)) {
2844
			$start = preg_quote($this->startQuote);
2845
		}
2846
		if (!empty($this->endQuote)) {
2847
			$end = preg_quote($this->endQuote);
2848
		}
2849
		$conditions = str_replace(array($start, $end), '', $conditions);
2850
		$conditions = preg_replace_callback(
2851
			'/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_][a-z0-9\\-_]*\\.[a-z0-9_][a-z0-9_\\-]*)/i',
2852
			array(&$this, '_quoteMatchedField'),
2853
			$conditions
2854
		);
2855
		if ($conditions !== null) {
2856
			return $conditions;
2857
		}
2858
		return $original;
2859
	}
2860
 
2861
/**
2862
 * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call
2863
 *
2864
 * @param string $match matched string
2865
 * @return string quoted string
2866
 */
2867
	protected function _quoteMatchedField($match) {
2868
		if (is_numeric($match[0])) {
2869
			return $match[0];
2870
		}
2871
		return $this->name($match[0]);
2872
	}
2873
 
2874
/**
2875
 * Returns a limit statement in the correct format for the particular database.
2876
 *
2877
 * @param int $limit Limit of results returned
2878
 * @param int $offset Offset from which to start results
2879
 * @return string SQL limit/offset statement
2880
 */
2881
	public function limit($limit, $offset = null) {
2882
		if ($limit) {
2883
			$rt = ' LIMIT';
2884
 
2885
			if ($offset) {
2886
				$rt .= sprintf(' %u,', $offset);
2887
			}
2888
 
2889
			$rt .= sprintf(' %u', $limit);
2890
			return $rt;
2891
		}
2892
		return null;
2893
	}
2894
 
2895
/**
2896
 * Returns an ORDER BY clause as a string.
2897
 *
2898
 * @param array|string $keys Field reference, as a key (i.e. Post.title)
2899
 * @param string $direction Direction (ASC or DESC)
2900
 * @param Model $Model Model reference (used to look for virtual field)
2901
 * @return string ORDER BY clause
2902
 */
2903
	public function order($keys, $direction = 'ASC', Model $Model = null) {
2904
		if (!is_array($keys)) {
2905
			$keys = array($keys);
2906
		}
2907
 
2908
		$keys = array_filter($keys);
2909
 
2910
		$result = array();
2911
		while (!empty($keys)) {
2912
			list($key, $dir) = each($keys);
2913
			array_shift($keys);
2914
 
2915
			if (is_numeric($key)) {
2916
				$key = $dir;
2917
				$dir = $direction;
2918
			}
2919
 
2920
			if (is_string($key) && strpos($key, ',') !== false && !preg_match('/\(.+\,.+\)/', $key)) {
2921
				$key = array_map('trim', explode(',', $key));
2922
			}
2923
 
2924
			if (is_array($key)) {
2925
				//Flatten the array
2926
				$key = array_reverse($key, true);
2927
				foreach ($key as $k => $v) {
2928
					if (is_numeric($k)) {
2929
						array_unshift($keys, $v);
2930
					} else {
2931
						$keys = array($k => $v) + $keys;
2932
					}
2933
				}
2934
				continue;
2935
			} elseif (is_object($key) && isset($key->type) && $key->type === 'expression') {
2936
				$result[] = $key->value;
2937
				continue;
2938
			}
2939
 
2940
			if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) {
2941
				$dir = $_dir[0];
2942
				$key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key);
2943
			}
2944
 
2945
			$key = trim($key);
2946
 
2947
			if ($Model !== null) {
2948
				if ($Model->isVirtualField($key)) {
2949
					$key = '(' . $this->_quoteFields($Model->getVirtualField($key)) . ')';
2950
				}
2951
 
2952
				list($alias) = pluginSplit($key);
2953
 
2954
				if ($alias !== $Model->alias && is_object($Model->{$alias}) && $Model->{$alias}->isVirtualField($key)) {
2955
					$key = '(' . $this->_quoteFields($Model->{$alias}->getVirtualField($key)) . ')';
2956
				}
2957
			}
2958
 
2959
			if (strpos($key, '.')) {
2960
				$key = preg_replace_callback('/([a-zA-Z0-9_-]{1,})\\.([a-zA-Z0-9_-]{1,})/', array(&$this, '_quoteMatchedField'), $key);
2961
			}
2962
 
2963
			if (!preg_match('/\s/', $key) && strpos($key, '.') === false) {
2964
				$key = $this->name($key);
2965
			}
2966
 
2967
			$key .= ' ' . trim($dir);
2968
 
2969
			$result[] = $key;
2970
		}
2971
 
2972
		if (!empty($result)) {
2973
			return ' ORDER BY ' . implode(', ', $result);
2974
		}
2975
 
2976
		return '';
2977
	}
2978
 
2979
/**
2980
 * Create a GROUP BY SQL clause.
2981
 *
2982
 * @param string|array $fields Group By fields
2983
 * @param Model $Model The model to get group by fields for.
2984
 * @return string Group By clause or null.
2985
 */
2986
	public function group($fields, Model $Model = null) {
2987
		if (empty($fields)) {
2988
			return null;
2989
		}
2990
 
2991
		if (!is_array($fields)) {
2992
			$fields = array($fields);
2993
		}
2994
 
2995
		if ($Model !== null) {
2996
			foreach ($fields as $index => $key) {
2997
				if ($Model->isVirtualField($key)) {
2998
					$fields[$index] = '(' . $Model->getVirtualField($key) . ')';
2999
				}
3000
			}
3001
		}
3002
 
3003
		$fields = implode(', ', $fields);
3004
 
3005
		return ' GROUP BY ' . $this->_quoteFields($fields);
3006
	}
3007
 
3008
/**
3009
 * Disconnects database, kills the connection and says the connection is closed.
3010
 *
3011
 * @return void
3012
 */
3013
	public function close() {
3014
		$this->disconnect();
3015
	}
3016
 
3017
/**
3018
 * Checks if the specified table contains any record matching specified SQL
3019
 *
3020
 * @param Model $Model Model to search
3021
 * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
3022
 * @return bool True if the table has a matching record, else false
3023
 */
3024
	public function hasAny(Model $Model, $sql) {
3025
		$sql = $this->conditions($sql);
3026
		$table = $this->fullTableName($Model);
3027
		$alias = $this->alias . $this->name($Model->alias);
3028
		$where = $sql ? "{$sql}" : ' WHERE 1 = 1';
3029
		$id = $Model->escapeField();
3030
 
3031
		$out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}");
3032
 
3033
		if (is_array($out)) {
3034
			return $out[0]['count'];
3035
		}
3036
		return false;
3037
	}
3038
 
3039
/**
3040
 * Gets the length of a database-native column description, or null if no length
3041
 *
3042
 * @param string $real Real database-layer column type (i.e. "varchar(255)")
3043
 * @return mixed An integer or string representing the length of the column, or null for unknown length.
3044
 */
3045
	public function length($real) {
3046
		if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
3047
			$col = str_replace(array(')', 'unsigned'), '', $real);
3048
			$limit = null;
3049
 
3050
			if (strpos($col, '(') !== false) {
3051
				list($col, $limit) = explode('(', $col);
3052
			}
3053
			if ($limit !== null) {
3054
				return intval($limit);
3055
			}
3056
			return null;
3057
		}
3058
 
3059
		$types = array(
3060
			'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
3061
		);
3062
 
3063
		list($real, $type, $length, $offset, $sign) = $result;
3064
		$typeArr = $type;
3065
		$type = $type[0];
3066
		$length = $length[0];
3067
		$offset = $offset[0];
3068
 
3069
		$isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
3070
		if ($isFloat && $offset) {
3071
			return $length . ',' . $offset;
3072
		}
3073
 
3074
		if (($real[0] == $type) && (count($real) === 1)) {
3075
			return null;
3076
		}
3077
 
3078
		if (isset($types[$type])) {
3079
			$length += $types[$type];
3080
			if (!empty($sign)) {
3081
				$length--;
3082
			}
3083
		} elseif (in_array($type, array('enum', 'set'))) {
3084
			$length = 0;
3085
			foreach ($typeArr as $key => $enumValue) {
3086
				if ($key === 0) {
3087
					continue;
3088
				}
3089
				$tmpLength = strlen($enumValue);
3090
				if ($tmpLength > $length) {
3091
					$length = $tmpLength;
3092
				}
3093
			}
3094
		}
3095
		return intval($length);
3096
	}
3097
 
3098
/**
3099
 * Translates between PHP boolean values and Database (faked) boolean values
3100
 *
3101
 * @param mixed $data Value to be translated
3102
 * @param bool $quote Whether or not the field should be cast to a string.
3103
 * @return string|bool Converted boolean value
3104
 */
3105
	public function boolean($data, $quote = false) {
3106
		if ($quote) {
3107
			return !empty($data) ? '1' : '0';
3108
		}
3109
		return !empty($data);
3110
	}
3111
 
3112
/**
3113
 * Inserts multiple values into a table
3114
 *
3115
 * @param string $table The table being inserted into.
3116
 * @param array $fields The array of field/column names being inserted.
3117
 * @param array $values The array of values to insert. The values should
3118
 *   be an array of rows. Each row should have values keyed by the column name.
3119
 *   Each row must have the values in the same order as $fields.
3120
 * @return bool
3121
 */
3122
	public function insertMulti($table, $fields, $values) {
3123
		$table = $this->fullTableName($table);
3124
		$holder = implode(',', array_fill(0, count($fields), '?'));
3125
		$fields = implode(', ', array_map(array(&$this, 'name'), $fields));
3126
 
3127
		$pdoMap = array(
3128
			'integer' => PDO::PARAM_INT,
3129
			'float' => PDO::PARAM_STR,
3130
			'boolean' => PDO::PARAM_BOOL,
3131
			'string' => PDO::PARAM_STR,
3132
			'text' => PDO::PARAM_STR
3133
		);
3134
		$columnMap = array();
3135
 
3136
		$sql = "INSERT INTO {$table} ({$fields}) VALUES ({$holder})";
3137
		$statement = $this->_connection->prepare($sql);
3138
		$this->begin();
3139
 
3140
		foreach ($values[key($values)] as $key => $val) {
3141
			$type = $this->introspectType($val);
3142
			$columnMap[$key] = $pdoMap[$type];
3143
		}
3144
 
3145
		foreach ($values as $value) {
3146
			$i = 1;
3147
			foreach ($value as $col => $val) {
3148
				$statement->bindValue($i, $val, $columnMap[$col]);
3149
				$i += 1;
3150
			}
3151
			$statement->execute();
3152
			$statement->closeCursor();
3153
 
3154
			if ($this->fullDebug) {
3155
				$this->logQuery($sql, $value);
3156
			}
3157
		}
3158
		return $this->commit();
3159
	}
3160
 
3161
/**
3162
 * Reset a sequence based on the MAX() value of $column. Useful
3163
 * for resetting sequences after using insertMulti().
3164
 *
3165
 * This method should be implemented by datasources that require sequences to be used.
3166
 *
3167
 * @param string $table The name of the table to update.
3168
 * @param string $column The column to use when resetting the sequence value.
3169
 * @return bool|void success.
3170
 */
3171
	public function resetSequence($table, $column) {
3172
	}
3173
 
3174
/**
3175
 * Returns an array of the indexes in given datasource name.
3176
 *
3177
 * @param string $model Name of model to inspect
3178
 * @return array Fields in table. Keys are column and unique
3179
 */
3180
	public function index($model) {
3181
		return array();
3182
	}
3183
 
3184
/**
3185
 * Generate a database-native schema for the given Schema object
3186
 *
3187
 * @param CakeSchema $schema An instance of a subclass of CakeSchema
3188
 * @param string $tableName Optional. If specified only the table name given will be generated.
3189
 *   Otherwise, all tables defined in the schema are generated.
3190
 * @return string
3191
 */
3192
	public function createSchema($schema, $tableName = null) {
3193
		if (!$schema instanceof CakeSchema) {
3194
			trigger_error(__d('cake_dev', 'Invalid schema object'), E_USER_WARNING);
3195
			return null;
3196
		}
3197
		$out = '';
3198
 
3199
		foreach ($schema->tables as $curTable => $columns) {
3200
			if (!$tableName || $tableName === $curTable) {
3201
				$cols = $indexes = $tableParameters = array();
3202
				$primary = null;
3203
				$table = $this->fullTableName($curTable);
3204
 
3205
				$primaryCount = 0;
3206
				foreach ($columns as $col) {
3207
					if (isset($col['key']) && $col['key'] === 'primary') {
3208
						$primaryCount++;
3209
					}
3210
				}
3211
 
3212
				foreach ($columns as $name => $col) {
3213
					if (is_string($col)) {
3214
						$col = array('type' => $col);
3215
					}
3216
					$isPrimary = isset($col['key']) && $col['key'] === 'primary';
3217
					// Multi-column primary keys are not supported.
3218
					if ($isPrimary && $primaryCount > 1) {
3219
						unset($col['key']);
3220
						$isPrimary = false;
3221
					}
3222
					if ($isPrimary) {
3223
						$primary = $name;
3224
					}
3225
					if ($name !== 'indexes' && $name !== 'tableParameters') {
3226
						$col['name'] = $name;
3227
						if (!isset($col['type'])) {
3228
							$col['type'] = 'string';
3229
						}
3230
						$cols[] = $this->buildColumn($col);
3231
					} elseif ($name === 'indexes') {
3232
						$indexes = array_merge($indexes, $this->buildIndex($col, $table));
3233
					} elseif ($name === 'tableParameters') {
3234
						$tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table));
3235
					}
3236
				}
3237
				if (!isset($columns['indexes']['PRIMARY']) && !empty($primary)) {
3238
					$col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
3239
					$indexes = array_merge($indexes, $this->buildIndex($col, $table));
3240
				}
3241
				$columns = $cols;
3242
				$out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n";
3243
			}
3244
		}
3245
		return $out;
3246
	}
3247
 
3248
/**
3249
 * Generate a alter syntax from CakeSchema::compare()
3250
 *
3251
 * @param mixed $compare The comparison data.
3252
 * @param string $table The table name.
3253
 * @return bool
3254
 */
3255
	public function alterSchema($compare, $table = null) {
3256
		return false;
3257
	}
3258
 
3259
/**
3260
 * Generate a "drop table" statement for the given Schema object
3261
 *
3262
 * @param CakeSchema $schema An instance of a subclass of CakeSchema
3263
 * @param string $table Optional. If specified only the table name given will be generated.
3264
 *   Otherwise, all tables defined in the schema are generated.
3265
 * @return string
3266
 */
3267
	public function dropSchema(CakeSchema $schema, $table = null) {
3268
		$out = '';
3269
 
3270
		if ($table && array_key_exists($table, $schema->tables)) {
3271
			return $this->_dropTable($table) . "\n";
3272
		} elseif ($table) {
3273
			return $out;
3274
		}
3275
 
3276
		foreach (array_keys($schema->tables) as $curTable) {
3277
			$out .= $this->_dropTable($curTable) . "\n";
3278
		}
3279
		return $out;
3280
	}
3281
 
3282
/**
3283
 * Generate a "drop table" statement for a single table
3284
 *
3285
 * @param type $table Name of the table to drop
3286
 * @return string Drop table SQL statement
3287
 */
3288
	protected function _dropTable($table) {
3289
		return 'DROP TABLE ' . $this->fullTableName($table) . ";";
3290
	}
3291
 
3292
/**
3293
 * Generate a database-native column schema string
3294
 *
3295
 * @param array $column An array structured like the following: array('name' => 'value', 'type' => 'value'[, options]),
3296
 *   where options can be 'default', 'length', or 'key'.
3297
 * @return string
3298
 */
3299
	public function buildColumn($column) {
3300
		$name = $type = null;
3301
		extract(array_merge(array('null' => true), $column));
3302
 
3303
		if (empty($name) || empty($type)) {
3304
			trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
3305
			return null;
3306
		}
3307
 
3308
		if (!isset($this->columns[$type])) {
3309
			trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
3310
			return null;
3311
		}
3312
 
3313
		$real = $this->columns[$type];
3314
		$out = $this->name($name) . ' ' . $real['name'];
3315
 
3316
		if (isset($column['length'])) {
3317
			$length = $column['length'];
3318
		} elseif (isset($column['limit'])) {
3319
			$length = $column['limit'];
3320
		} elseif (isset($real['length'])) {
3321
			$length = $real['length'];
3322
		} elseif (isset($real['limit'])) {
3323
			$length = $real['limit'];
3324
		}
3325
		if (isset($length)) {
3326
			$out .= '(' . $length . ')';
3327
		}
3328
 
3329
		if (($column['type'] === 'integer' || $column['type'] === 'float') && isset($column['default']) && $column['default'] === '') {
3330
			$column['default'] = null;
3331
		}
3332
		$out = $this->_buildFieldParameters($out, $column, 'beforeDefault');
3333
 
3334
		if (isset($column['key']) && $column['key'] === 'primary' && ($type === 'integer' || $type === 'biginteger')) {
3335
			$out .= ' ' . $this->columns['primary_key']['name'];
3336
		} elseif (isset($column['key']) && $column['key'] === 'primary') {
3337
			$out .= ' NOT NULL';
3338
		} elseif (isset($column['default']) && isset($column['null']) && $column['null'] === false) {
3339
			$out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
3340
		} elseif (isset($column['default'])) {
3341
			$out .= ' DEFAULT ' . $this->value($column['default'], $type);
3342
		} elseif ($type !== 'timestamp' && !empty($column['null'])) {
3343
			$out .= ' DEFAULT NULL';
3344
		} elseif ($type === 'timestamp' && !empty($column['null'])) {
3345
			$out .= ' NULL';
3346
		} elseif (isset($column['null']) && $column['null'] === false) {
3347
			$out .= ' NOT NULL';
3348
		}
3349
		if ($type === 'timestamp' && isset($column['default']) && strtolower($column['default']) === 'current_timestamp') {
3350
			$out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out);
3351
		}
3352
		return $this->_buildFieldParameters($out, $column, 'afterDefault');
3353
	}
3354
 
3355
/**
3356
 * Build the field parameters, in a position
3357
 *
3358
 * @param string $columnString The partially built column string
3359
 * @param array $columnData The array of column data.
3360
 * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common
3361
 * @return string a built column with the field parameters added.
3362
 */
3363
	protected function _buildFieldParameters($columnString, $columnData, $position) {
3364
		foreach ($this->fieldParameters as $paramName => $value) {
3365
			if (isset($columnData[$paramName]) && $value['position'] == $position) {
3366
				if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'], true)) {
3367
					continue;
3368
				}
3369
				if (isset($value['types']) && !in_array($columnData['type'], $value['types'], true)) {
3370
					continue;
3371
				}
3372
				$val = $columnData[$paramName];
3373
				if ($value['quote']) {
3374
					$val = $this->value($val);
3375
				}
3376
				$columnString .= ' ' . $value['value'] . (empty($value['noVal']) ? $value['join'] . $val : '');
3377
			}
3378
		}
3379
		return $columnString;
3380
	}
3381
 
3382
/**
3383
 * Format indexes for create table.
3384
 *
3385
 * @param array $indexes The indexes to build
3386
 * @param string $table The table name.
3387
 * @return array
3388
 */
3389
	public function buildIndex($indexes, $table = null) {
3390
		$join = array();
3391
		foreach ($indexes as $name => $value) {
3392
			$out = '';
3393
			if ($name === 'PRIMARY') {
3394
				$out .= 'PRIMARY ';
3395
				$name = null;
3396
			} else {
3397
				if (!empty($value['unique'])) {
3398
					$out .= 'UNIQUE ';
3399
				}
3400
				$name = $this->startQuote . $name . $this->endQuote;
3401
			}
3402
			if (is_array($value['column'])) {
3403
				$out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
3404
			} else {
3405
				$out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')';
3406
			}
3407
			$join[] = $out;
3408
		}
3409
		return $join;
3410
	}
3411
 
3412
/**
3413
 * Read additional table parameters
3414
 *
3415
 * @param string $name The table name to read.
3416
 * @return array
3417
 */
3418
	public function readTableParameters($name) {
3419
		$parameters = array();
3420
		if (method_exists($this, 'listDetailedSources')) {
3421
			$currentTableDetails = $this->listDetailedSources($name);
3422
			foreach ($this->tableParameters as $paramName => $parameter) {
3423
				if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) {
3424
					$parameters[$paramName] = $currentTableDetails[$parameter['column']];
3425
				}
3426
			}
3427
		}
3428
		return $parameters;
3429
	}
3430
 
3431
/**
3432
 * Format parameters for create table
3433
 *
3434
 * @param array $parameters The parameters to create SQL for.
3435
 * @param string $table The table name.
3436
 * @return array
3437
 */
3438
	public function buildTableParameters($parameters, $table = null) {
3439
		$result = array();
3440
		foreach ($parameters as $name => $value) {
3441
			if (isset($this->tableParameters[$name])) {
3442
				if ($this->tableParameters[$name]['quote']) {
3443
					$value = $this->value($value);
3444
				}
3445
				$result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value;
3446
			}
3447
		}
3448
		return $result;
3449
	}
3450
 
3451
/**
3452
 * Guesses the data type of an array
3453
 *
3454
 * @param string $value The value to introspect for type data.
3455
 * @return string
3456
 */
3457
	public function introspectType($value) {
3458
		if (!is_array($value)) {
3459
			if (is_bool($value)) {
3460
				return 'boolean';
3461
			}
3462
			if (is_float($value) && floatval($value) === $value) {
3463
				return 'float';
3464
			}
3465
			if (is_int($value) && intval($value) === $value) {
3466
				return 'integer';
3467
			}
3468
			if (is_string($value) && strlen($value) > 255) {
3469
				return 'text';
3470
			}
3471
			return 'string';
3472
		}
3473
 
3474
		$isAllFloat = $isAllInt = true;
3475
		$containsInt = $containsString = false;
3476
		foreach ($value as $valElement) {
3477
			$valElement = trim($valElement);
3478
			if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
3479
				$isAllFloat = false;
3480
			} else {
3481
				continue;
3482
			}
3483
			if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
3484
				$isAllInt = false;
3485
			} else {
3486
				$containsInt = true;
3487
				continue;
3488
			}
3489
			$containsString = true;
3490
		}
3491
 
3492
		if ($isAllFloat) {
3493
			return 'float';
3494
		}
3495
		if ($isAllInt) {
3496
			return 'integer';
3497
		}
3498
 
3499
		if ($containsInt && !$containsString) {
3500
			return 'integer';
3501
		}
3502
		return 'string';
3503
	}
3504
 
3505
/**
3506
 * Writes a new key for the in memory sql query cache
3507
 *
3508
 * @param string $sql SQL query
3509
 * @param mixed $data result of $sql query
3510
 * @param array $params query params bound as values
3511
 * @return void
3512
 */
3513
	protected function _writeQueryCache($sql, $data, $params = array()) {
3514
		if (preg_match('/^\s*select/i', $sql)) {
3515
			$this->_queryCache[$sql][serialize($params)] = $data;
3516
		}
3517
	}
3518
 
3519
/**
3520
 * Returns the result for a sql query if it is already cached
3521
 *
3522
 * @param string $sql SQL query
3523
 * @param array $params query params bound as values
3524
 * @return mixed results for query if it is cached, false otherwise
3525
 */
3526
	public function getQueryCache($sql, $params = array()) {
3527
		if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
3528
			$serialized = serialize($params);
3529
			if (isset($this->_queryCache[$sql][$serialized])) {
3530
				return $this->_queryCache[$sql][$serialized];
3531
			}
3532
		}
3533
		return false;
3534
	}
3535
 
3536
/**
3537
 * Used for storing in cache the results of the in-memory methodCache
3538
 */
3539
	public function __destruct() {
3540
		if ($this->_methodCacheChange) {
3541
			Cache::write('method_cache', self::$methodCache, '_cake_core_');
3542
		}
3543
	}
3544
 
3545
}