Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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