Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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