Subversion-Projekte lars-tiefland.cakephp

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/* SVN FILE: $Id: dbo_source.php 8004 2009-01-16 20:15:21Z gwoo $ */
3
/**
4
 * Short description for file.
5
 *
6
 * Long description for file
7
 *
8
 * PHP versions 4 and 5
9
 *
10
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
11
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
12
 *
13
 * Licensed under The MIT License
14
 * Redistributions of files must retain the above copyright notice.
15
 *
16
 * @filesource
17
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
18
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
19
 * @package       cake
20
 * @subpackage    cake.cake.libs.model.datasources
21
 * @since         CakePHP(tm) v 0.10.0.1076
22
 * @version       $Revision: 8004 $
23
 * @modifiedby    $LastChangedBy: gwoo $
24
 * @lastmodified  $Date: 2009-01-16 12:15:21 -0800 (Fri, 16 Jan 2009) $
25
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
26
 */
27
App::import('Core', array('Set', 'String'));
28
 
29
/**
30
 * DboSource
31
 *
32
 * Creates DBO-descendant objects from a given db connection configuration
33
 *
34
 * @package       cake
35
 * @subpackage    cake.cake.libs.model.datasources
36
 */
37
class DboSource extends DataSource {
38
/**
39
 * Description string for this Database Data Source.
40
 *
41
 * @var unknown_type
42
 */
43
	var $description = "Database Data Source";
44
/**
45
 * index definition, standard cake, primary, index, unique
46
 *
47
 * @var array
48
 */
49
	var $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
50
/**
51
 * Database keyword used to assign aliases to identifiers.
52
 *
53
 * @var string
54
 */
55
	var $alias = 'AS ';
56
/**
57
 * Caches fields quoted in DboSource::name()
58
 *
59
 * @var array
60
 */
61
	var $fieldCache = array();
62
/**
63
 * Bypass automatic adding of joined fields/associations.
64
 *
65
 * @var boolean
66
 */
67
	var $__bypass = false;
68
/**
69
 * The set of valid SQL operations usable in a WHERE statement
70
 *
71
 * @var array
72
 */
73
	var $__sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
74
/**
75
 * Index of basic SQL commands
76
 *
77
 * @var array
78
 * @access protected
79
 */
80
	var $_commands = array(
81
		'begin'	   => 'BEGIN',
82
		'commit'   => 'COMMIT',
83
		'rollback' => 'ROLLBACK'
84
	);
85
/**
86
 * Constructor
87
 */
88
	function __construct($config = null, $autoConnect = true) {
89
		if (!isset($config['prefix'])) {
90
			$config['prefix'] = '';
91
		}
92
		parent::__construct($config);
93
		$this->fullDebug = Configure::read() > 1;
94
 
95
		if ($autoConnect) {
96
			return $this->connect();
97
		} else {
98
			return true;
99
		}
100
	}
101
/**
102
 * Reconnects to database server with optional new settings
103
 *
104
 * @param array $config An array defining the new configuration settings
105
 * @return boolean True on success, false on failure
106
 */
107
	function reconnect($config = null) {
108
		$this->disconnect();
109
		$this->setConfig($config);
110
		$this->_sources = null;
111
 
112
		return $this->connect();
113
	}
114
/**
115
 * Prepares a value, or an array of values for database queries by quoting and escaping them.
116
 *
117
 * @param mixed $data A value or an array of values to prepare.
118
 * @param string $column The column into which this data will be inserted
119
 * @param boolean $read Value to be used in READ or WRITE context
120
 * @return mixed Prepared value or array of values.
121
 */
122
	function value($data, $column = null, $read = true) {
123
		if (is_array($data) && !empty($data)) {
124
			return array_map(
125
				array(&$this, 'value'),
126
				$data, array_fill(0, count($data), $column), array_fill(0, count($data), $read)
127
			);
128
		} elseif (is_object($data) && isset($data->type)) {
129
			if ($data->type == 'identifier') {
130
				return $this->name($data->value);
131
			} elseif ($data->type == 'expression') {
132
				return $data->value;
133
			}
134
		} elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
135
			return $data;
136
		} else {
137
			return null;
138
		}
139
	}
140
/**
141
 * Returns an object to represent a database identifier in a query
142
 *
143
 * @param string $identifier
144
 * @return object An object representing a database identifier to be used in a query
145
 */
146
	function identifier($identifier) {
147
		$obj = new stdClass();
148
		$obj->type = 'identifier';
149
		$obj->value = $identifier;
150
		return $obj;
151
	}
152
/**
153
 * Returns an object to represent a database expression in a query
154
 *
155
 * @param string $expression
156
 * @return object An object representing a database expression to be used in a query
157
 */
158
	function expression($expression) {
159
		$obj = new stdClass();
160
		$obj->type = 'expression';
161
		$obj->value = $expression;
162
		return $obj;
163
	}
164
/**
165
 * Executes given SQL statement.
166
 *
167
 * @param string $sql SQL statement
168
 * @return unknown
169
 */
170
	function rawQuery($sql) {
171
		$this->took = $this->error = $this->numRows = false;
172
		return $this->execute($sql);
173
	}
174
/**
175
 * Queries the database with given SQL statement, and obtains some metadata about the result
176
 * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
177
 * If DEBUG is set, the log is shown all the time, else it is only shown on errors.
178
 *
179
 * @param string $sql
180
 * @param array $options
181
 * @return mixed Resource or object representing the result set, or false on failure
182
 */
183
	function execute($sql, $options = array()) {
184
		$defaults = array('stats' => true, 'log' => $this->fullDebug);
185
		$options = array_merge($defaults, $options);
186
 
187
		if ($options['stats']) {
188
			$t = getMicrotime();
189
			$this->_result = $this->_execute($sql);
190
			$this->took = round((getMicrotime() - $t) * 1000, 0);
191
			$this->affected = $this->lastAffected();
192
			$this->error = $this->lastError();
193
			$this->numRows = $this->lastNumRows();
194
		}
195
 
196
		if ($options['log']) {
197
			$this->logQuery($sql);
198
		}
199
 
200
		if ($this->error) {
201
			$this->showQuery($sql);
202
			return false;
203
		} else {
204
			return $this->_result;
205
		}
206
	}
207
/**
208
 * DataSource Query abstraction
209
 *
210
 * @return resource Result resource identifier
211
 */
212
	function query() {
213
		$args	  = func_get_args();
214
		$fields	  = null;
215
		$order	  = null;
216
		$limit	  = null;
217
		$page	  = null;
218
		$recursive = null;
219
 
220
		if (count($args) == 1) {
221
			return $this->fetchAll($args[0]);
222
 
223
		} elseif (count($args) > 1 && (strpos(strtolower($args[0]), 'findby') === 0 || strpos(strtolower($args[0]), 'findallby') === 0)) {
224
			$params = $args[1];
225
 
226
			if (strpos(strtolower($args[0]), 'findby') === 0) {
227
				$all  = false;
228
				$field = Inflector::underscore(preg_replace('/findBy/i', '', $args[0]));
229
			} else {
230
				$all  = true;
231
				$field = Inflector::underscore(preg_replace('/findAllBy/i', '', $args[0]));
232
			}
233
 
234
			$or = (strpos($field, '_or_') !== false);
235
			if ($or) {
236
				$field = explode('_or_', $field);
237
			} else {
238
				$field = explode('_and_', $field);
239
			}
240
			$off = count($field) - 1;
241
 
242
			if (isset($params[1 + $off])) {
243
				$fields = $params[1 + $off];
244
			}
245
 
246
			if (isset($params[2 + $off])) {
247
				$order = $params[2 + $off];
248
			}
249
 
250
			if (!array_key_exists(0, $params)) {
251
				return false;
252
			}
253
 
254
			$c = 0;
255
			$conditions = array();
256
 
257
			foreach ($field as $f) {
258
				$conditions[$args[2]->alias . '.' . $f] = $params[$c];
259
				$c++;
260
			}
261
 
262
			if ($or) {
263
				$conditions = array('OR' => $conditions);
264
			}
265
 
266
			if ($all) {
267
				if (isset($params[3 + $off])) {
268
					$limit = $params[3 + $off];
269
				}
270
 
271
				if (isset($params[4 + $off])) {
272
					$page = $params[4 + $off];
273
				}
274
 
275
				if (isset($params[5 + $off])) {
276
					$recursive = $params[5 + $off];
277
				}
278
				return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
279
			} else {
280
				if (isset($params[3 + $off])) {
281
					$recursive = $params[3 + $off];
282
				}
283
				return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
284
			}
285
		} else {
286
			if (isset($args[1]) && $args[1] === true) {
287
				return $this->fetchAll($args[0], true);
288
			} else if (isset($args[1]) && !is_array($args[1]) ) {
289
				return $this->fetchAll($args[0], false);
290
			} else if (isset($args[1]) && is_array($args[1])) {
291
				$offset = 0;
292
				if (isset($args[2])) {
293
					$cache = $args[2];
294
				} else {
295
					$cache = true;
296
				}
297
				$args[1] = array_map(array(&$this, 'value'), $args[1]);
298
				return $this->fetchAll(String::insert($args[0], $args[1]), $cache);
299
			}
300
		}
301
	}
302
/**
303
 * Returns a row from current resultset as an array
304
 *
305
 * @return array The fetched row as an array
306
 */
307
	function fetchRow($sql = null) {
308
		if (!empty($sql) && is_string($sql) && strlen($sql) > 5) {
309
			if (!$this->execute($sql)) {
310
				return null;
311
			}
312
		}
313
 
314
		if ($this->hasResult()) {
315
			$this->resultSet($this->_result);
316
			$resultRow = $this->fetchResult();
317
			return $resultRow;
318
		} else {
319
			return null;
320
		}
321
	}
322
/**
323
 * Returns an array of all result rows for a given SQL query.
324
 * Returns false if no rows matched.
325
 *
326
 * @param string $sql SQL statement
327
 * @param boolean $cache Enables returning/storing cached query results
328
 * @return array Array of resultset rows, or false if no rows matched
329
 */
330
	function fetchAll($sql, $cache = true, $modelName = null) {
331
		if ($cache && isset($this->_queryCache[$sql])) {
332
			if (preg_match('/^\s*select/i', $sql)) {
333
				return $this->_queryCache[$sql];
334
			}
335
		}
336
 
337
		if ($this->execute($sql)) {
338
			$out = array();
339
 
340
			$first = $this->fetchRow();
341
			if ($first != null) {
342
				$out[] = $first;
343
			}
344
			while ($this->hasResult() && $item = $this->fetchResult()) {
345
				$out[] = $item;
346
			}
347
 
348
			if ($cache) {
349
				if (strpos(trim(strtolower($sql)), 'select') !== false) {
350
					$this->_queryCache[$sql] = $out;
351
				}
352
			}
353
			return $out;
354
 
355
		} else {
356
			return false;
357
		}
358
	}
359
/**
360
 * Returns a single field of the first of query results for a given SQL query, or false if empty.
361
 *
362
 * @param string $name Name of the field
363
 * @param string $sql SQL query
364
 * @return unknown
365
 */
366
	function field($name, $sql) {
367
		$data = $this->fetchRow($sql);
368
 
369
		if (!isset($data[$name]) || empty($data[$name])) {
370
			return false;
371
		} else {
372
			return $data[$name];
373
		}
374
	}
375
/**
376
 * Returns a quoted name of $data for use in an SQL statement.
377
 * Strips fields out of SQL functions before quoting.
378
 *
379
 * @param string $data
380
 * @return string SQL field
381
 */
382
	function name($data) {
383
		if ($data == '*') {
384
			return '*';
385
		}
386
		if (is_object($data) && isset($data->type)) {
387
			return $data->value;
388
		}
389
		$array = is_array($data);
390
		$data = (array)$data;
391
		$count = count($data);
392
 
393
		for ($i = 0; $i < $count; $i++) {
394
			if ($data[$i] == '*') {
395
				continue;
396
			}
397
			if (strpos($data[$i], '(') !== false && preg_match_all('/([^(]*)\((.*)\)(.*)/', $data[$i], $fields)) {
398
				$fields = Set::extract($fields, '{n}.0');
399
 
400
				if (!empty($fields[1])) {
401
					if (!empty($fields[2])) {
402
						$data[$i] = $fields[1] . '(' . $this->name($fields[2]) . ')' . $fields[3];
403
					} else {
404
						$data[$i] = $fields[1] . '()' . $fields[3];
405
					}
406
				}
407
			}
408
			$data[$i] = str_replace('.', $this->endQuote . '.' . $this->startQuote, $data[$i]);
409
			$data[$i] = $this->startQuote . $data[$i] . $this->endQuote;
410
			$data[$i] = str_replace($this->startQuote . $this->startQuote, $this->startQuote, $data[$i]);
411
			$data[$i] = str_replace($this->startQuote . '(', '(', $data[$i]);
412
			$data[$i] = str_replace(')' . $this->startQuote, ')', $data[$i]);
413
 
414
			if (strpos($data[$i], ' AS ')) {
415
				$data[$i] = str_replace(' AS ', $this->endQuote . ' AS ' . $this->startQuote, $data[$i]);
416
			}
417
			if (!empty($this->endQuote) && $this->endQuote == $this->startQuote) {
418
				if (substr_count($data[$i], $this->endQuote) % 2 == 1) {
419
					$data[$i] = trim($data[$i], $this->endQuote);
420
				}
421
			}
422
			if (strpos($data[$i], '*')) {
423
				$data[$i] = str_replace($this->endQuote . '*' . $this->endQuote, '*', $data[$i]);
424
			}
425
			$data[$i] = str_replace($this->endQuote . $this->endQuote, $this->endQuote, $data[$i]);
426
		}
427
		return (!$array) ? $data[0] : $data;
428
	}
429
/**
430
 * Checks if it's connected to the database
431
 *
432
 * @return boolean True if the database is connected, else false
433
 */
434
	function isConnected() {
435
		return $this->connected;
436
	}
437
/**
438
 * Checks if the result is valid
439
 *
440
 * @return boolean True if the result is valid else false
441
 */
442
	function hasResult() {
443
		return is_resource($this->_result);
444
	}
445
/**
446
 * Outputs the contents of the queries log.
447
 *
448
 * @param boolean $sorted
449
 */
450
	function showLog($sorted = false) {
451
		if ($sorted) {
452
			$log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
453
		} else {
454
			$log = $this->_queriesLog;
455
		}
456
 
457
		if ($this->_queriesCnt > 1) {
458
			$text = 'queries';
459
		} else {
460
			$text = 'query';
461
		}
462
 
463
		if (PHP_SAPI != 'cli') {
464
			print ("<table class=\"cake-sql-log\" id=\"cakeSqlLog_" . preg_replace('/[^A-Za-z0-9_]/', '_', uniqid(time(), true)) . "\" summary=\"Cake SQL Log\" cellspacing=\"0\" border = \"0\">\n<caption>({$this->configKeyName}) {$this->_queriesCnt} {$text} took {$this->_queriesTime} ms</caption>\n");
465
			print ("<thead>\n<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>\n</thead>\n<tbody>\n");
466
 
467
			foreach ($log as $k => $i) {
468
				print ("<tr><td>" . ($k + 1) . "</td><td>" . h($i['query']) . "</td><td>{$i['error']}</td><td style = \"text-align: right\">{$i['affected']}</td><td style = \"text-align: right\">{$i['numRows']}</td><td style = \"text-align: right\">{$i['took']}</td></tr>\n");
469
			}
470
			print ("</tbody></table>\n");
471
		} else {
472
			foreach ($log as $k => $i) {
473
				print (($k + 1) . ". {$i['query']} {$i['error']}\n");
474
			}
475
		}
476
	}
477
/**
478
 * Log given SQL query.
479
 *
480
 * @param string $sql SQL statement
481
 * @todo: Add hook to log errors instead of returning false
482
 */
483
	function logQuery($sql) {
484
		$this->_queriesCnt++;
485
		$this->_queriesTime += $this->took;
486
		$this->_queriesLog[] = array(
487
			'query' => $sql,
488
			'error'		=> $this->error,
489
			'affected'	=> $this->affected,
490
			'numRows'	=> $this->numRows,
491
			'took'		=> $this->took
492
		);
493
		if (count($this->_queriesLog) > $this->_queriesLogMax) {
494
			array_pop($this->_queriesLog);
495
		}
496
		if ($this->error) {
497
			return false;
498
		}
499
	}
500
/**
501
 * Output information about an SQL query. The SQL statement, number of rows in resultset,
502
 * and execution time in microseconds. If the query fails, an error is output instead.
503
 *
504
 * @param string $sql Query to show information on.
505
 */
506
	function showQuery($sql) {
507
		$error = $this->error;
508
		if (strlen($sql) > 200 && !$this->fullDebug && Configure::read() > 1) {
509
			$sql = substr($sql, 0, 200) . '[...]';
510
		}
511
		if (Configure::read() > 0) {
512
			$out = null;
513
			if ($error) {
514
				trigger_error("<span style = \"color:Red;text-align:left\"><b>SQL Error:</b> {$this->error}</span>", E_USER_WARNING);
515
			} else {
516
				$out = ("<small>[Aff:{$this->affected} Num:{$this->numRows} Took:{$this->took}ms]</small>");
517
			}
518
			pr(sprintf("<p style = \"text-align:left\"><b>Query:</b> %s %s</p>", $sql, $out));
519
		}
520
	}
521
/**
522
 * Gets full table name including prefix
523
 *
524
 * @param mixed $model
525
 * @param boolean $quote
526
 * @return string Full quoted table name
527
 */
528
	function fullTableName($model, $quote = true) {
529
		if (is_object($model)) {
530
			$table = $model->tablePrefix . $model->table;
531
		} elseif (isset($this->config['prefix'])) {
532
			$table = $this->config['prefix'] . strval($model);
533
		} else {
534
			$table = strval($model);
535
		}
536
		if ($quote) {
537
			return $this->name($table);
538
		}
539
		return $table;
540
	}
541
/**
542
 * The "C" in CRUD
543
 *
544
 * @param Model $model
545
 * @param array $fields
546
 * @param array $values
547
 * @return boolean Success
548
 */
549
	function create(&$model, $fields = null, $values = null) {
550
		$id = null;
551
 
552
		if ($fields == null) {
553
			unset($fields, $values);
554
			$fields = array_keys($model->data);
555
			$values = array_values($model->data);
556
		}
557
		$count = count($fields);
558
 
559
		for ($i = 0; $i < $count; $i++) {
560
			$valueInsert[] = $this->value($values[$i], $model->getColumnType($fields[$i]), false);
561
		}
562
		for ($i = 0; $i < $count; $i++) {
563
			$fieldInsert[] = $this->name($fields[$i]);
564
			if ($fields[$i] == $model->primaryKey) {
565
				$id = $values[$i];
566
			}
567
		}
568
		$query = array(
569
			'table' => $this->fullTableName($model),
570
			'fields' => join(', ', $fieldInsert),
571
			'values' => join(', ', $valueInsert)
572
		);
573
 
574
		if ($this->execute($this->renderStatement('create', $query))) {
575
			if (empty($id)) {
576
				$id = $this->lastInsertId($this->fullTableName($model, false), $model->primaryKey);
577
			}
578
			$model->setInsertID($id);
579
			$model->id = $id;
580
			return true;
581
		} else {
582
			$model->onError();
583
			return false;
584
		}
585
	}
586
/**
587
 * The "R" in CRUD
588
 *
589
 * @param Model $model
590
 * @param array $queryData
591
 * @param integer $recursive Number of levels of association
592
 * @return unknown
593
 */
594
	function read(&$model, $queryData = array(), $recursive = null) {
595
		$queryData = $this->__scrubQueryData($queryData);
596
 
597
		$null = null;
598
		$array = array();
599
		$linkedModels = array();
600
		$this->__bypass = false;
601
		$this->__booleans = array();
602
 
603
		if ($recursive === null && isset($queryData['recursive'])) {
604
			$recursive = $queryData['recursive'];
605
		}
606
 
607
		if (!is_null($recursive)) {
608
			$_recursive = $model->recursive;
609
			$model->recursive = $recursive;
610
		}
611
 
612
		if (!empty($queryData['fields'])) {
613
			$this->__bypass = true;
614
			$queryData['fields'] = $this->fields($model, null, $queryData['fields']);
615
		} else {
616
			$queryData['fields'] = $this->fields($model);
617
		}
618
 
619
		foreach ($model->__associations as $type) {
620
			foreach ($model->{$type} as $assoc => $assocData) {
621
				if ($model->recursive > -1) {
622
					$linkModel =& $model->{$assoc};
623
					$external = isset($assocData['external']);
624
 
625
					if ($model->useDbConfig == $linkModel->useDbConfig) {
626
						if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
627
							$linkedModels[] = $type . '/' . $assoc;
628
						}
629
					}
630
				}
631
			}
632
		}
633
 
634
		$query = $this->generateAssociationQuery($model, $null, null, null, null, $queryData, false, $null);
635
 
636
		$resultSet = $this->fetchAll($query, $model->cacheQueries, $model->alias);
637
 
638
		if ($resultSet === false) {
639
			$model->onError();
640
			return false;
641
		}
642
 
643
		$filtered = $this->__filterResults($resultSet, $model);
644
 
645
		if ($model->recursive > 0) {
646
			foreach ($model->__associations as $type) {
647
				foreach ($model->{$type} as $assoc => $assocData) {
648
					$linkModel =& $model->{$assoc};
649
 
650
					if (!in_array($type . '/' . $assoc, $linkedModels)) {
651
						if ($model->useDbConfig == $linkModel->useDbConfig) {
652
							$db =& $this;
653
						} else {
654
							$db =& ConnectionManager::getDataSource($linkModel->useDbConfig);
655
						}
656
					} elseif ($model->recursive > 1 && ($type == 'belongsTo' || $type == 'hasOne')) {
657
						$db =& $this;
658
					}
659
 
660
					if (isset($db)) {
661
						$stack = array($assoc);
662
						$db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
663
						unset($db);
664
					}
665
				}
666
			}
667
			$this->__filterResults($resultSet, $model, $filtered);
668
		}
669
 
670
		if (!is_null($recursive)) {
671
			$model->recursive = $_recursive;
672
		}
673
		return $resultSet;
674
	}
675
/**
676
 * Private method.	Passes association results thru afterFind filters of corresponding model
677
 *
678
 * @param array $results Reference of resultset to be filtered
679
 * @param object $model Instance of model to operate against
680
 * @param array $filtered List of classes already filtered, to be skipped
681
 * @return return
682
 */
683
	function __filterResults(&$results, &$model, $filtered = array()) {
684
		$filtering = array();
685
		$count = count($results);
686
 
687
		for ($i = 0; $i < $count; $i++) {
688
			if (is_array($results[$i])) {
689
				$classNames = array_keys($results[$i]);
690
				$count2 = count($classNames);
691
 
692
				for ($j = 0; $j < $count2; $j++) {
693
					$className = $classNames[$j];
694
					if ($model->alias != $className && !in_array($className, $filtered)) {
695
						if (!in_array($className, $filtering)) {
696
							$filtering[] = $className;
697
						}
698
 
699
						if (isset($model->{$className}) && is_object($model->{$className})) {
700
							$data = $model->{$className}->afterFind(array(array($className => $results[$i][$className])), false);
701
						}
702
						if (isset($data[0][$className])) {
703
							$results[$i][$className] = $data[0][$className];
704
						}
705
					}
706
				}
707
			}
708
		}
709
		return $filtering;
710
	}
711
/**
712
 * Enter description here...
713
 *
714
 * @param Model $model
715
 * @param unknown_type $linkModel
716
 * @param string $type Association type
717
 * @param unknown_type $association
718
 * @param unknown_type $assocData
719
 * @param unknown_type $queryData
720
 * @param unknown_type $external
721
 * @param unknown_type $resultSet
722
 * @param integer $recursive Number of levels of association
723
 * @param array $stack
724
 */
725
	function queryAssociation(&$model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) {
726
		if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
727
			if (!isset($resultSet) || !is_array($resultSet)) {
728
				if (Configure::read() > 0) {
729
					e('<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:', true), $model->alias) . ' ');
730
					if (isset($this->error) && $this->error != null) {
731
						e($this->error);
732
					}
733
					e('</div>');
734
				}
735
				return null;
736
			}
737
			$count = count($resultSet);
738
 
739
			if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
740
				$ins = $fetch = array();
741
				for ($i = 0; $i < $count; $i++) {
742
					if ($in = $this->insertQueryData('{$__cakeID__$}', $resultSet[$i], $association, $assocData, $model, $linkModel, $stack)) {
743
						$ins[] = $in;
744
					}
745
				}
746
 
747
				if (!empty($ins)) {
748
					$fetch = $this->fetchAssociated($model, $query, $ins);
749
				}
750
 
751
				if (!empty($fetch) && is_array($fetch)) {
752
					if ($recursive > 0) {
753
						foreach ($linkModel->__associations as $type1) {
754
							foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
755
								$deepModel =& $linkModel->{$assoc1};
756
								$tmpStack = $stack;
757
								$tmpStack[] = $assoc1;
758
 
759
								if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
760
									$db =& $this;
761
								} else {
762
									$db =& ConnectionManager::getDataSource($deepModel->useDbConfig);
763
								}
764
								$db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
765
							}
766
						}
767
					}
768
				}
769
				$this->__filterResults($fetch, $model);
770
				return $this->__mergeHasMany($resultSet, $fetch, $association, $model, $linkModel, $recursive);
771
			} elseif ($type === 'hasAndBelongsToMany') {
772
				$ins = $fetch = array();
773
				for ($i = 0; $i < $count; $i++) {
774
					if ($in = $this->insertQueryData('{$__cakeID__$}', $resultSet[$i], $association, $assocData, $model, $linkModel, $stack)) {
775
						$ins[] = $in;
776
					}
777
				}
778
				if (!empty($ins)) {
779
					if (count($ins) > 1) {
780
						$query = str_replace('{$__cakeID__$}', '(' .join(', ', $ins) .')', $query);
781
						$query = str_replace('= (', 'IN (', $query);
782
						$query = str_replace('=	 (', 'IN (', $query);
783
					} else {
784
						$query = str_replace('{$__cakeID__$}',$ins[0], $query);
785
					}
786
 
787
					$query = str_replace('	WHERE 1 = 1', '', $query);
788
				}
789
 
790
				$foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
791
				$joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
792
				list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
793
				$habtmFieldsCount = count($habtmFields);
794
				$q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
795
 
796
				if ($q != false) {
797
					$fetch = $this->fetchAll($q, $model->cacheQueries, $model->alias);
798
				} else {
799
					$fetch = null;
800
				}
801
			}
802
 
803
			for ($i = 0; $i < $count; $i++) {
804
				$row =& $resultSet[$i];
805
 
806
				if ($type !== 'hasAndBelongsToMany') {
807
					$q = $this->insertQueryData($query, $resultSet[$i], $association, $assocData, $model, $linkModel, $stack);
808
					if ($q != false) {
809
						$fetch = $this->fetchAll($q, $model->cacheQueries, $model->alias);
810
					} else {
811
						$fetch = null;
812
					}
813
				}
814
				$selfJoin = false;
815
 
816
				if ($linkModel->name === $model->name) {
817
					$selfJoin = true;
818
				}
819
 
820
				if (!empty($fetch) && is_array($fetch)) {
821
					if ($recursive > 0) {
822
						foreach ($linkModel->__associations as $type1) {
823
							foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
824
								$deepModel =& $linkModel->{$assoc1};
825
 
826
								if (($type1 === 'belongsTo') || ($deepModel->alias === $model->alias && $type === 'belongsTo') || ($deepModel->alias != $model->alias)) {
827
									$tmpStack = $stack;
828
									$tmpStack[] = $assoc1;
829
									if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
830
										$db =& $this;
831
									} else {
832
										$db =& ConnectionManager::getDataSource($deepModel->useDbConfig);
833
									}
834
									$db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
835
								}
836
							}
837
						}
838
					}
839
					if ($type == 'hasAndBelongsToMany') {
840
						$uniqueIds = $merge = array();
841
 
842
						foreach ($fetch as $j => $data) {
843
							if (
844
								(isset($data[$with]) && $data[$with][$foreignKey] === $row[$model->alias][$model->primaryKey]) &&
845
								(!in_array($data[$with][$joinKeys[1]], $uniqueIds))
846
							) {
847
								$uniqueIds[] = $data[$with][$joinKeys[1]];
848
 
849
								if ($habtmFieldsCount <= 2) {
850
									unset($data[$with]);
851
								}
852
								$merge[] = $data;
853
							}
854
						}
855
						if (empty($merge) && !isset($row[$association])) {
856
							$row[$association] = $merge;
857
						} else {
858
							$this->__mergeAssociation($resultSet[$i], $merge, $association, $type);
859
						}
860
					} else {
861
						$this->__mergeAssociation($resultSet[$i], $fetch, $association, $type, $selfJoin);
862
					}
863
					if (isset($resultSet[$i][$association])) {
864
						$resultSet[$i][$association] = $linkModel->afterFind($resultSet[$i][$association]);
865
					}
866
				} else {
867
					$tempArray[0][$association] = false;
868
					$this->__mergeAssociation($resultSet[$i], $tempArray, $association, $type, $selfJoin);
869
				}
870
			}
871
		}
872
	}
873
/**
874
 * A more efficient way to fetch associations.	Woohoo!
875
 *
876
 * @param model $model		Primary model object
877
 * @param string $query		Association query
878
 * @param array $ids		Array of IDs of associated records
879
 * @return array Association results
880
 */
881
	function fetchAssociated($model, $query, $ids) {
882
		$query = str_replace('{$__cakeID__$}', join(', ', $ids), $query);
883
		if (count($ids) > 1) {
884
			$query = str_replace('= (', 'IN (', $query);
885
			$query = str_replace('=	 (', 'IN (', $query);
886
		}
887
		return $this->fetchAll($query, $model->cacheQueries, $model->alias);
888
	}
889
/**
890
 * mergeHasMany - Merge the results of hasMany relations.
891
 *
892
 *
893
 * @param array $resultSet Data to merge into
894
 * @param array $merge Data to merge
895
 * @param string $association Name of Model being Merged
896
 * @param object $model Model being merged onto
897
 * @param object $linkModel Model being merged
898
 * @return void
899
 **/
900
	function __mergeHasMany(&$resultSet, $merge, $association, &$model, &$linkModel) {
901
		foreach ($resultSet as $i => $value) {
902
			$count = 0;
903
			$merged[$association] = array();
904
			foreach ($merge as $j => $data) {
905
				if (isset($value[$model->alias]) && $value[$model->alias][$model->primaryKey] === $data[$association][$model->hasMany[$association]['foreignKey']]) {
906
					if (count($data) > 1) {
907
						$data = array_merge($data[$association], $data);
908
						unset($data[$association]);
909
						foreach ($data as $key => $name) {
910
							if (is_numeric($key)) {
911
								$data[$association][] = $name;
912
								unset($data[$key]);
913
							}
914
						}
915
						$merged[$association][] = $data;
916
					} else {
917
						$merged[$association][] = $data[$association];
918
					}
919
				}
920
				$count++;
921
			}
922
			if (isset($value[$model->alias])) {
923
				$resultSet[$i] = Set::pushDiff($resultSet[$i], $merged);
924
				unset($merged);
925
			}
926
		}
927
	}
928
/**
929
 * Enter description here...
930
 *
931
 * @param unknown_type $data
932
 * @param unknown_type $merge
933
 * @param unknown_type $association
934
 * @param unknown_type $type
935
 * @param boolean $selfJoin
936
 */
937
	function __mergeAssociation(&$data, $merge, $association, $type, $selfJoin = false) {
938
		if (isset($merge[0]) && !isset($merge[0][$association])) {
939
			$association = Inflector::pluralize($association);
940
		}
941
 
942
		if ($type == 'belongsTo' || $type == 'hasOne') {
943
			if (isset($merge[$association])) {
944
				$data[$association] = $merge[$association][0];
945
			} else {
946
				if (count($merge[0][$association]) > 1) {
947
					foreach ($merge[0] as $assoc => $data2) {
948
						if ($assoc != $association) {
949
							$merge[0][$association][$assoc] = $data2;
950
						}
951
					}
952
				}
953
				if (!isset($data[$association])) {
954
					if ($merge[0][$association] != null) {
955
						$data[$association] = $merge[0][$association];
956
					} else {
957
						$data[$association] = array();
958
					}
959
				} else {
960
					if (is_array($merge[0][$association])) {
961
						foreach ($data[$association] as $k => $v) {
962
							if (!is_array($v)) {
963
								$dataAssocTmp[$k] = $v;
964
							}
965
						}
966
 
967
						foreach ($merge[0][$association] as $k => $v) {
968
							if (!is_array($v)) {
969
								$mergeAssocTmp[$k] = $v;
970
							}
971
						}
972
						$dataKeys = array_keys($data);
973
						$mergeKeys = array_keys($merge[0]);
974
 
975
						if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
976
							$data[$association][$association] = $merge[0][$association];
977
						} else {
978
							$diff = Set::diff($dataAssocTmp, $mergeAssocTmp);
979
							$data[$association] = array_merge($merge[0][$association], $diff);
980
						}
981
					} elseif ($selfJoin && array_key_exists($association, $merge[0])) {
982
						$data[$association] = array_merge($data[$association], array($association => array()));
983
					}
984
				}
985
			}
986
		} else {
987
			if (isset($merge[0][$association]) && $merge[0][$association] === false) {
988
				if (!isset($data[$association])) {
989
					$data[$association] = array();
990
				}
991
			} else {
992
				foreach ($merge as $i => $row) {
993
					if (count($row) == 1) {
994
						if (empty($data[$association]) || (isset($data[$association]) && !in_array($row[$association], $data[$association]))) {
995
							$data[$association][] = $row[$association];
996
						}
997
					} else if (!empty($row)) {
998
						$tmp = array_merge($row[$association], $row);
999
						unset($tmp[$association]);
1000
						$data[$association][] = $tmp;
1001
					}
1002
				}
1003
			}
1004
		}
1005
	}
1006
/**
1007
 * Generates an array representing a query or part of a query from a single model or two associated models
1008
 *
1009
 * @param Model $model
1010
 * @param Model $linkModel
1011
 * @param string $type
1012
 * @param string $association
1013
 * @param array $assocData
1014
 * @param array $queryData
1015
 * @param boolean $external
1016
 * @param array $resultSet
1017
 * @return mixed
1018
 */
1019
	function generateAssociationQuery(&$model, &$linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) {
1020
		$queryData = $this->__scrubQueryData($queryData);
1021
		$assocData = $this->__scrubQueryData($assocData);
1022
 
1023
		if (empty($queryData['fields'])) {
1024
			$queryData['fields'] = $this->fields($model, $model->alias);
1025
		} elseif (!empty($model->hasMany) && $model->recursive > -1) {
1026
			$assocFields = $this->fields($model, $model->alias, array("{$model->alias}.{$model->primaryKey}"));
1027
			$passedFields = $this->fields($model, $model->alias, $queryData['fields']);
1028
 
1029
			if (count($passedFields) === 1) {
1030
				$match = strpos($passedFields[0], $assocFields[0]);
1031
				$match1 = strpos($passedFields[0], 'COUNT(');
1032
				if ($match === false && $match1 === false) {
1033
					$queryData['fields'] = array_merge($passedFields, $assocFields);
1034
				} else {
1035
					$queryData['fields'] = $passedFields;
1036
				}
1037
			} else {
1038
				$queryData['fields'] = array_merge($passedFields, $assocFields);
1039
			}
1040
			unset($assocFields, $passedFields);
1041
		}
1042
 
1043
		if ($linkModel == null) {
1044
			return $this->buildStatement(
1045
				array(
1046
					'fields' => array_unique($queryData['fields']),
1047
					'table' => $this->fullTableName($model),
1048
					'alias' => $model->alias,
1049
					'limit' => $queryData['limit'],
1050
					'offset' => $queryData['offset'],
1051
					'joins' => $queryData['joins'],
1052
					'conditions' => $queryData['conditions'],
1053
					'order' => $queryData['order'],
1054
					'group' => $queryData['group']
1055
				),
1056
				$model
1057
			);
1058
		}
1059
		if ($external && !empty($assocData['finderQuery'])) {
1060
			return $assocData['finderQuery'];
1061
		}
1062
 
1063
		$alias = $association;
1064
		$self = ($model->name == $linkModel->name);
1065
		$fields = array();
1066
 
1067
		if ((!$external && in_array($type, array('hasOne', 'belongsTo')) && $this->__bypass === false) || $external) {
1068
			$fields = $this->fields($linkModel, $alias, $assocData['fields']);
1069
		}
1070
		if (empty($assocData['offset']) && !empty($assocData['page'])) {
1071
			$assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
1072
		}
1073
		$assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']);
1074
 
1075
		switch ($type) {
1076
			case 'hasOne':
1077
			case 'belongsTo':
1078
				$conditions = $this->__mergeConditions(
1079
					$assocData['conditions'],
1080
					$this->getConstraint($type, $model, $linkModel, $alias, array_merge($assocData, compact('external', 'self')))
1081
				);
1082
 
1083
				if (!$self && $external) {
1084
					foreach ($conditions as $key => $condition) {
1085
						if (is_numeric($key) && strpos($condition, $model->alias . '.') !== false) {
1086
							unset($conditions[$key]);
1087
						}
1088
					}
1089
				}
1090
 
1091
				if ($external) {
1092
					$query = array_merge($assocData, array(
1093
						'conditions' => $conditions,
1094
						'table' => $this->fullTableName($linkModel),
1095
						'fields' => $fields,
1096
						'alias' => $alias,
1097
						'group' => null
1098
					));
1099
					$query = array_merge(array('order' => $assocData['order'], 'limit' => $assocData['limit']), $query);
1100
				} else {
1101
					$join = array(
1102
						'table' => $this->fullTableName($linkModel),
1103
						'alias' => $alias,
1104
						'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
1105
						'conditions' => trim($this->conditions($conditions, true, false, $model))
1106
					);
1107
					$queryData['fields'] = array_merge($queryData['fields'], $fields);
1108
 
1109
					if (!empty($assocData['order'])) {
1110
						$queryData['order'][] = $assocData['order'];
1111
					}
1112
					if (!in_array($join, $queryData['joins'])) {
1113
						$queryData['joins'][] = $join;
1114
					}
1115
					return true;
1116
				}
1117
			break;
1118
			case 'hasMany':
1119
				$assocData['fields'] = $this->fields($linkModel, $alias, $assocData['fields']);
1120
				if (!empty($assocData['foreignKey'])) {
1121
					$assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $alias, array("{$alias}.{$assocData['foreignKey']}")));
1122
				}
1123
				$query = array(
1124
					'conditions' => $this->__mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $alias, $assocData), $assocData['conditions']),
1125
					'fields' => array_unique($assocData['fields']),
1126
					'table' => $this->fullTableName($linkModel),
1127
					'alias' => $alias,
1128
					'order' => $assocData['order'],
1129
					'limit' => $assocData['limit'],
1130
					'group' => null
1131
				);
1132
			break;
1133
			case 'hasAndBelongsToMany':
1134
				$joinFields = array();
1135
				$joinAssoc = null;
1136
 
1137
				if (isset($assocData['with']) && !empty($assocData['with'])) {
1138
					$joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
1139
					list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
1140
 
1141
					$joinTbl = $this->fullTableName($model->{$with});
1142
					$joinAlias = $joinTbl;
1143
 
1144
					if (is_array($joinFields) && !empty($joinFields)) {
1145
						$joinFields = $this->fields($model->{$with}, $model->{$with}->alias, $joinFields);
1146
						$joinAssoc = $joinAlias = $model->{$with}->alias;
1147
					} else {
1148
						$joinFields = array();
1149
					}
1150
				} else {
1151
					$joinTbl = $this->fullTableName($assocData['joinTable']);
1152
					$joinAlias = $joinTbl;
1153
				}
1154
				$query = array(
1155
					'conditions' => $assocData['conditions'],
1156
					'limit' => $assocData['limit'],
1157
					'table' => $this->fullTableName($linkModel),
1158
					'alias' => $alias,
1159
					'fields' => array_merge($this->fields($linkModel, $alias, $assocData['fields']), $joinFields),
1160
					'order' => $assocData['order'],
1161
					'group' => null,
1162
					'joins' => array(array(
1163
						'table' => $joinTbl,
1164
						'alias' => $joinAssoc,
1165
						'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $alias)
1166
					))
1167
				);
1168
			break;
1169
		}
1170
		if (isset($query)) {
1171
			return $this->buildStatement($query, $model);
1172
		}
1173
		return null;
1174
	}
1175
/**
1176
 * Returns a conditions array for the constraint between two models
1177
 *
1178
 * @param string $type Association type
1179
 * @param object $model Model object
1180
 * @param array $association Association array
1181
 * @return array Conditions array defining the constraint between $model and $association
1182
 */
1183
	function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
1184
		$assoc = array_merge(array('external' => false, 'self' => false), $assoc);
1185
 
1186
		if (array_key_exists('foreignKey', $assoc) && empty($assoc['foreignKey'])) {
1187
			return array();
1188
		}
1189
 
1190
		switch (true) {
1191
			case ($assoc['external'] && $type == 'hasOne'):
1192
				return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
1193
			break;
1194
			case ($assoc['external'] && $type == 'belongsTo'):
1195
				return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
1196
			break;
1197
			case (!$assoc['external'] && $type == 'hasOne'):
1198
				return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
1199
			break;
1200
			case (!$assoc['external'] && $type == 'belongsTo'):
1201
				return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
1202
			break;
1203
			case ($type == 'hasMany'):
1204
				return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
1205
			break;
1206
			case ($type == 'hasAndBelongsToMany'):
1207
				return array(
1208
					array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
1209
					array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
1210
				);
1211
			break;
1212
		}
1213
		return array();
1214
	}
1215
/**
1216
 * Builds and generates a JOIN statement from an array.	 Handles final clean-up before conversion.
1217
 *
1218
 * @param array $join An array defining a JOIN statement in a query
1219
 * @return string An SQL JOIN statement to be used in a query
1220
 * @see DboSource::renderJoinStatement()
1221
 * @see DboSource::buildStatement()
1222
 */
1223
	function buildJoinStatement($join) {
1224
		$data = array_merge(array(
1225
			'type' => null,
1226
			'alias' => null,
1227
			'table' => 'join_table',
1228
			'conditions' => array()
1229
		), $join);
1230
 
1231
		if (!empty($data['alias'])) {
1232
			$data['alias'] = $this->alias . $this->name($data['alias']);
1233
		}
1234
		if (!empty($data['conditions'])) {
1235
			$data['conditions'] = trim($this->conditions($data['conditions'], true, false));
1236
		}
1237
		return $this->renderJoinStatement($data);
1238
	}
1239
/**
1240
 * Builds and generates an SQL statement from an array.	 Handles final clean-up before conversion.
1241
 *
1242
 * @param array $query An array defining an SQL query
1243
 * @param object $model The model object which initiated the query
1244
 * @return string An executable SQL statement
1245
 * @see DboSource::renderStatement()
1246
 */
1247
	function buildStatement($query, $model) {
1248
		$query = array_merge(array('offset' => null, 'joins' => array()), $query);
1249
		if (!empty($query['joins'])) {
1250
			$count = count($query['joins']);
1251
			for ($i = 0; $i < $count; $i++) {
1252
				if (is_array($query['joins'][$i])) {
1253
					$query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]);
1254
				}
1255
			}
1256
		}
1257
		return $this->renderStatement('select', array(
1258
			'conditions' => $this->conditions($query['conditions'], true, true, $model),
1259
			'fields' => join(', ', $query['fields']),
1260
			'table' => $query['table'],
1261
			'alias' => $this->alias . $this->name($query['alias']),
1262
			'order' => $this->order($query['order']),
1263
			'limit' => $this->limit($query['limit'], $query['offset']),
1264
			'joins' => join(' ', $query['joins']),
1265
			'group' => $this->group($query['group'])
1266
		));
1267
	}
1268
/**
1269
 * Renders a final SQL JOIN statement
1270
 *
1271
 * @param array $data
1272
 * @return string
1273
 */
1274
	function renderJoinStatement($data) {
1275
		extract($data);
1276
		return trim("{$type} JOIN {$table} {$alias} ON ({$conditions})");
1277
	}
1278
/**
1279
 * Renders a final SQL statement by putting together the component parts in the correct order
1280
 *
1281
 * @param string $type
1282
 * @param array $data
1283
 * @return string
1284
 */
1285
	function renderStatement($type, $data) {
1286
		extract($data);
1287
		$aliases = null;
1288
 
1289
		switch (strtolower($type)) {
1290
			case 'select':
1291
				return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}";
1292
			break;
1293
			case 'create':
1294
				return "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
1295
			break;
1296
			case 'update':
1297
				if (!empty($alias)) {
1298
					$aliases = "{$this->alias}{$alias} {$joins} ";
1299
				}
1300
				return "UPDATE {$table} {$aliases}SET {$fields} {$conditions}";
1301
			break;
1302
			case 'delete':
1303
				if (!empty($alias)) {
1304
					$aliases = "{$this->alias}{$alias} {$joins} ";
1305
				}
1306
				return "DELETE {$alias} FROM {$table} {$aliases}{$conditions}";
1307
			break;
1308
			case 'schema':
1309
				foreach (array('columns', 'indexes') as $var) {
1310
					if (is_array(${$var})) {
1311
						${$var} = "\t" . join(",\n\t", array_filter(${$var}));
1312
					}
1313
				}
1314
				if (trim($indexes) != '') {
1315
					$columns .= ',';
1316
				}
1317
				return "CREATE TABLE {$table} (\n{$columns}{$indexes});";
1318
			break;
1319
			case 'alter':
1320
			break;
1321
		}
1322
	}
1323
/**
1324
 * Merges a mixed set of string/array conditions
1325
 *
1326
 * @return array
1327
 */
1328
	function __mergeConditions($query, $assoc) {
1329
		if (empty($assoc)) {
1330
			return $query;
1331
		}
1332
 
1333
		if (is_array($query)) {
1334
			return array_merge((array)$assoc, $query);
1335
		}
1336
 
1337
		if (!empty($query)) {
1338
			$query = array($query);
1339
			if (is_array($assoc)) {
1340
				$query = array_merge($query, $assoc);
1341
			} else {
1342
				$query[] = $assoc;
1343
			}
1344
			return $query;
1345
		}
1346
 
1347
		return $assoc;
1348
	}
1349
/**
1350
 * Generates and executes an SQL UPDATE statement for given model, fields, and values.
1351
 * For databases that do not support aliases in UPDATE queries.
1352
 *
1353
 * @param Model $model
1354
 * @param array $fields
1355
 * @param array $values
1356
 * @param mixed $conditions
1357
 * @return boolean Success
1358
 */
1359
	function update(&$model, $fields = array(), $values = null, $conditions = null) {
1360
		if ($values == null) {
1361
			$combined = $fields;
1362
		} else {
1363
			$combined = array_combine($fields, $values);
1364
		}
1365
		$fields = join(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions)));
1366
 
1367
		$alias = $joins = null;
1368
		$table = $this->fullTableName($model);
1369
		$conditions = $this->_matchRecords($model, $conditions);
1370
 
1371
		if ($conditions === false) {
1372
			return false;
1373
		}
1374
		$query = compact('table', 'alias', 'joins', 'fields', 'conditions');
1375
 
1376
		if (!$this->execute($this->renderStatement('update', $query))) {
1377
			$model->onError();
1378
			return false;
1379
		}
1380
		return true;
1381
	}
1382
/**
1383
 * Quotes and prepares fields and values for an SQL UPDATE statement
1384
 *
1385
 * @param Model $model
1386
 * @param array $fields
1387
 * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets
1388
 * @param boolean $alias Include the model alias in the field name
1389
 * @return array Fields and values, quoted and preparted
1390
 * @access protected
1391
 */
1392
	function _prepareUpdateFields(&$model, $fields, $quoteValues = true, $alias = false) {
1393
		$quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
1394
 
1395
		foreach ($fields as $field => $value) {
1396
			if ($alias && strpos($field, '.') === false) {
1397
				$quoted = $model->escapeField($field);
1398
			} elseif (!$alias && strpos($field, '.') !== false) {
1399
				$quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace(
1400
					$model->alias . '.', '', $field
1401
				)));
1402
			} else {
1403
				$quoted = $this->name($field);
1404
			}
1405
 
1406
			if ($value === null) {
1407
				$updates[] = $quoted . ' = NULL';
1408
				continue;
1409
			}
1410
			$update = $quoted . ' = ';
1411
 
1412
			if ($quoteValues) {
1413
				$update .= $this->value($value, $model->getColumnType($field), false);
1414
			} elseif (!$alias) {
1415
				$update .= str_replace($quotedAlias . '.', '', str_replace(
1416
					$model->alias . '.', '', $value
1417
				));
1418
			} else {
1419
				$update .= $value;
1420
			}
1421
			$updates[] =  $update;
1422
		}
1423
		return $updates;
1424
	}
1425
/**
1426
 * Generates and executes an SQL DELETE statement.
1427
 * For databases that do not support aliases in UPDATE queries.
1428
 *
1429
 * @param Model $model
1430
 * @param mixed $conditions
1431
 * @return boolean Success
1432
 */
1433
	function delete(&$model, $conditions = null) {
1434
		$alias = $joins = null;
1435
		$table = $this->fullTableName($model);
1436
		$conditions = $this->_matchRecords($model, $conditions);
1437
 
1438
		if ($conditions === false) {
1439
			return false;
1440
		}
1441
 
1442
		if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) {
1443
			$model->onError();
1444
			return false;
1445
		}
1446
		return true;
1447
	}
1448
/**
1449
 * Gets a list of record IDs for the given conditions.	Used for multi-record updates and deletes
1450
 * in databases that do not support aliases in UPDATE/DELETE queries.
1451
 *
1452
 * @param Model $model
1453
 * @param mixed $conditions
1454
 * @return array List of record IDs
1455
 * @access protected
1456
 */
1457
	function _matchRecords(&$model, $conditions = null) {
1458
		if ($conditions === true) {
1459
			$conditions = $this->conditions(true);
1460
		} elseif ($conditions === null) {
1461
			$conditions = $this->conditions($this->defaultConditions($model, $conditions, false), true, true, $model);
1462
		} else {
1463
			$idList = $model->find('all', array(
1464
				'fields' => "{$model->alias}.{$model->primaryKey}",
1465
				'conditions' => $conditions
1466
			));
1467
 
1468
			if (empty($idList)) {
1469
				return false;
1470
			}
1471
			$conditions = $this->conditions(array(
1472
				$model->primaryKey => Set::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
1473
			));
1474
		}
1475
		return $conditions;
1476
	}
1477
/**
1478
 * Returns an array of SQL JOIN fragments from a model's associations
1479
 *
1480
 * @param object $model
1481
 * @return array
1482
 */
1483
	function _getJoins($model) {
1484
		$join = array();
1485
		$joins = array_merge($model->getAssociated('hasOne'), $model->getAssociated('belongsTo'));
1486
 
1487
		foreach ($joins as $assoc) {
1488
			if (isset($model->{$assoc}) && $model->useDbConfig == $model->{$assoc}->useDbConfig) {
1489
				$assocData = $model->getAssociated($assoc);
1490
				$join[] = $this->buildJoinStatement(array(
1491
					'table' => $this->fullTableName($model->{$assoc}),
1492
					'alias' => $assoc,
1493
					'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
1494
					'conditions' => trim($this->conditions(
1495
						$this->getConstraint($assocData['association'], $model, $model->{$assoc}, $assoc, $assocData),
1496
						true, false, $model
1497
					))
1498
				));
1499
			}
1500
		}
1501
		return $join;
1502
	}
1503
/**
1504
 * Returns the an SQL calculation, i.e. COUNT() or MAX()
1505
 *
1506
 * @param model $model
1507
 * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max'
1508
 * @param array $params Function parameters (any values must be quoted manually)
1509
 * @return string	An SQL calculation function
1510
 * @access public
1511
 */
1512
	function calculate(&$model, $func, $params = array()) {
1513
		$params = (array)$params;
1514
 
1515
		switch (strtolower($func)) {
1516
			case 'count':
1517
				if (!isset($params[0])) {
1518
					$params[0] = '*';
1519
				}
1520
				if (!isset($params[1])) {
1521
					$params[1] = 'count';
1522
				}
1523
				return 'COUNT(' . $this->name($params[0]) . ') AS ' . $this->name($params[1]);
1524
			case 'max':
1525
			case 'min':
1526
				if (!isset($params[1])) {
1527
					$params[1] = $params[0];
1528
				}
1529
				return strtoupper($func) . '(' . $this->name($params[0]) . ') AS ' . $this->name($params[1]);
1530
			break;
1531
		}
1532
	}
1533
/**
1534
 * Deletes all the records in a table and resets the count of the auto-incrementing
1535
 * primary key, where applicable.
1536
 *
1537
 * @param mixed $table A string or model class representing the table to be truncated
1538
 * @return boolean	SQL TRUNCATE TABLE statement, false if not applicable.
1539
 * @access public
1540
 */
1541
	function truncate($table) {
1542
		return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table));
1543
	}
1544
/**
1545
 * Begin a transaction
1546
 *
1547
 * @param model $model
1548
 * @return boolean True on success, false on fail
1549
 * (i.e. if the database/model does not support transactions,
1550
 * or a transaction has not started).
1551
 */
1552
	function begin(&$model) {
1553
		if (parent::begin($model) && $this->execute($this->_commands['begin'])) {
1554
			$this->_transactionStarted = true;
1555
			return true;
1556
		}
1557
		return false;
1558
	}
1559
/**
1560
 * Commit a transaction
1561
 *
1562
 * @param model $model
1563
 * @return boolean True on success, false on fail
1564
 * (i.e. if the database/model does not support transactions,
1565
 * or a transaction has not started).
1566
 */
1567
	function commit(&$model) {
1568
		if (parent::commit($model) && $this->execute($this->_commands['commit'])) {
1569
			$this->_transactionStarted = false;
1570
			return true;
1571
		}
1572
		return false;
1573
	}
1574
/**
1575
 * Rollback a transaction
1576
 *
1577
 * @param model $model
1578
 * @return boolean True on success, false on fail
1579
 * (i.e. if the database/model does not support transactions,
1580
 * or a transaction has not started).
1581
 */
1582
	function rollback(&$model) {
1583
		if (parent::rollback($model) && $this->execute($this->_commands['rollback'])) {
1584
			$this->_transactionStarted = false;
1585
			return true;
1586
		}
1587
		return false;
1588
	}
1589
/**
1590
 * Creates a default set of conditions from the model if $conditions is null/empty.
1591
 *
1592
 * @param object $model
1593
 * @param mixed	 $conditions
1594
 * @param boolean $useAlias Use model aliases rather than table names when generating conditions
1595
 * @return mixed
1596
 */
1597
	function defaultConditions(&$model, $conditions, $useAlias = true) {
1598
		if (!empty($conditions)) {
1599
			return $conditions;
1600
		}
1601
		if (!$model->exists()) {
1602
			return false;
1603
		}
1604
		$alias = $model->alias;
1605
 
1606
		if (!$useAlias) {
1607
			$alias = $this->fullTableName($model, false);
1608
		}
1609
		return array("{$alias}.{$model->primaryKey}" => $model->getID());
1610
	}
1611
/**
1612
 * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name)
1613
 *
1614
 * @param unknown_type $model
1615
 * @param unknown_type $key
1616
 * @param unknown_type $assoc
1617
 * @return string
1618
 */
1619
	function resolveKey($model, $key, $assoc = null) {
1620
		if (empty($assoc)) {
1621
			$assoc = $model->alias;
1622
		}
1623
		if (!strpos('.', $key)) {
1624
			return $this->name($model->alias) . '.' . $this->name($key);
1625
		}
1626
		return $key;
1627
	}
1628
/**
1629
 * Private helper method to remove query metadata in given data array.
1630
 *
1631
 * @param array $data
1632
 * @return array
1633
 */
1634
	function __scrubQueryData($data) {
1635
		foreach (array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group') as $key) {
1636
			if (!isset($data[$key]) || empty($data[$key])) {
1637
				$data[$key] = array();
1638
			}
1639
		}
1640
		return $data;
1641
	}
1642
/**
1643
 * Generates the fields list of an SQL query.
1644
 *
1645
 * @param Model $model
1646
 * @param string $alias Alias tablename
1647
 * @param mixed $fields
1648
 * @param boolean $quote If false, returns fields array unquoted
1649
 * @return array
1650
 */
1651
	function fields(&$model, $alias = null, $fields = array(), $quote = true) {
1652
		if (empty($alias)) {
1653
			$alias = $model->alias;
1654
		}
1655
		if (empty($fields)) {
1656
			$fields = array_keys($model->schema());
1657
		} elseif (!is_array($fields)) {
1658
			$fields = String::tokenize($fields);
1659
		}
1660
		$fields = array_values(array_filter($fields));
1661
 
1662
		if (!$quote) {
1663
			return $fields;
1664
		}
1665
		$count = count($fields);
1666
 
1667
		if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) {
1668
			for ($i = 0; $i < $count; $i++) {
1669
				if (!preg_match('/^.+\\(.*\\)/', $fields[$i])) {
1670
					$prepend = '';
1671
 
1672
					if (strpos($fields[$i], 'DISTINCT') !== false) {
1673
						$prepend = 'DISTINCT ';
1674
						$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
1675
					}
1676
					$dot = strpos($fields[$i], '.');
1677
 
1678
					if ($dot === false) {
1679
						$prefix = !(
1680
							strpos($fields[$i], ' ') !== false ||
1681
							strpos($fields[$i], '(') !== false
1682
						);
1683
						$fields[$i] = $this->name(($prefix ? '' : '') . $alias . '.' . $fields[$i]);
1684
					} else {
1685
						$value = array();
1686
						$comma = strpos($fields[$i], ',');
1687
						if ($comma === false) {
1688
							$build = explode('.', $fields[$i]);
1689
							if (!Set::numeric($build)) {
1690
								$fields[$i] = $this->name($build[0] . '.' . $build[1]);
1691
							}
1692
							$comma = String::tokenize($fields[$i]);
1693
							foreach ($comma as $string) {
1694
								if (preg_match('/^[0-9]+\.[0-9]+$/', $string)) {
1695
									$value[] = $string;
1696
								} else {
1697
									$build = explode('.', $string);
1698
									$value[] = $this->name(trim($build[0]) . '.' . trim($build[1]));
1699
								}
1700
							}
1701
							$fields[$i] = implode(', ', $value);
1702
						}
1703
					}
1704
					$fields[$i] = $prepend . $fields[$i];
1705
				} elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) {
1706
					if (isset($field[1])) {
1707
						if (strpos($field[1], '.') === false) {
1708
							$field[1] = $this->name($alias . '.' . $field[1]);
1709
						} else {
1710
							$field[0] = explode('.', $field[1]);
1711
							if (!Set::numeric($field[0])) {
1712
								$field[0] = join('.', array_map(array($this, 'name'), $field[0]));
1713
								$fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
1714
							}
1715
						}
1716
					}
1717
				}
1718
			}
1719
		}
1720
		return array_unique($fields);
1721
	}
1722
/**
1723
 * Creates a WHERE clause by parsing given conditions data.
1724
 *
1725
 * @param mixed $conditions Array or string of conditions
1726
 * @param boolean $quoteValues If true, values should be quoted
1727
 * @param boolean $where If true, "WHERE " will be prepended to the return value
1728
 * @param Model $model A reference to the Model instance making the query
1729
 * @return string SQL fragment
1730
 */
1731
	function conditions($conditions, $quoteValues = true, $where = true, $model = null) {
1732
		$clause = $out = '';
1733
 
1734
		if ($where) {
1735
			$clause = ' WHERE ';
1736
		}
1737
 
1738
		if (is_array($conditions) && !empty($conditions)) {
1739
			$out = $this->conditionKeysToString($conditions, $quoteValues, $model);
1740
 
1741
			if (empty($out)) {
1742
				return $clause . ' 1 = 1';
1743
			}
1744
			return $clause . join(' AND ', $out);
1745
		}
1746
 
1747
		if (empty($conditions) || trim($conditions) == '' || $conditions === true) {
1748
			return $clause . '1 = 1';
1749
		}
1750
		$clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i';
1751
 
1752
		if (preg_match($clauses, $conditions, $match)) {
1753
			$clause = '';
1754
		}
1755
		if (trim($conditions) == '') {
1756
			$conditions = ' 1 = 1';
1757
		} else {
1758
			$conditions = $this->__quoteFields($conditions);
1759
		}
1760
		return $clause . $conditions;
1761
	}
1762
/**
1763
 * Creates a WHERE clause by parsing given conditions array.  Used by DboSource::conditions().
1764
 *
1765
 * @param array $conditions Array or string of conditions
1766
 * @param boolean $quoteValues If true, values should be quoted
1767
 * @param Model $model A reference to the Model instance making the query
1768
 * @return string SQL fragment
1769
 */
1770
	function conditionKeysToString($conditions, $quoteValues = true, $model = null) {
1771
		$c = 0;
1772
		$out = array();
1773
		$data = $columnType = null;
1774
		$bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&');
1775
 
1776
		foreach ($conditions as $key => $value) {
1777
			$join = ' AND ';
1778
			$not = null;
1779
 
1780
			if (is_array($value)) {
1781
				$valueInsert = (
1782
					!empty($value) &&
1783
					(substr_count($key, '?') == count($value) || substr_count($key, ':') == count($value))
1784
				);
1785
			}
1786
 
1787
			if (is_numeric($key) && empty($value)) {
1788
				continue;
1789
			} elseif (is_numeric($key) && is_string($value)) {
1790
				$out[] = $not . $this->__quoteFields($value);
1791
			} elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) {
1792
				if (in_array(strtolower(trim($key)), $bool)) {
1793
					$join = ' ' . strtoupper($key) . ' ';
1794
				} else {
1795
					$key = $join;
1796
				}
1797
				$value = $this->conditionKeysToString($value, $quoteValues, $model);
1798
 
1799
				if (strpos($join, 'NOT') !== false) {
1800
					if (strtoupper(trim($key)) == 'NOT') {
1801
						$key = 'AND ' . trim($key);
1802
					}
1803
					$not = 'NOT ';
1804
				}
1805
 
1806
				if (empty($value[1])) {
1807
					if ($not) {
1808
						$out[] = $not . '(' . $value[0] . ')';
1809
					} else {
1810
						$out[] = $value[0] ;
1811
					}
1812
				} else {
1813
					$out[] = '(' . $not . '(' . join(') ' . strtoupper($key) . ' (', $value) . '))';
1814
				}
1815
 
1816
			} else {
1817
				if (is_object($value) && isset($value->type)) {
1818
					if ($value->type == 'identifier') {
1819
						$data .= $this->name($key) . ' = ' . $this->name($value->value);
1820
					} elseif ($value->type == 'expression') {
1821
						if (is_numeric($key)) {
1822
							$data .= $value->value;
1823
						} else {
1824
							$data .= $this->name($key) . ' = ' . $value->value;
1825
						}
1826
					}
1827
				} elseif (is_array($value) && !empty($value) && !$valueInsert) {
1828
					$keys = array_keys($value);
1829
					if (array_keys($value) === array_values(array_keys($value))) {
1830
						$count = count($value);
1831
						if ($count === 1) {
1832
							$data = $this->name($key) . ' = (';
1833
						} else {
1834
							$data = $this->name($key) . ' IN (';
1835
						}
1836
						if ($quoteValues || strpos($value[0], '-!') !== 0) {
1837
							if (is_object($model)) {
1838
								$columnType = $model->getColumnType($key);
1839
							}
1840
							$data .= join(', ', $this->value($value, $columnType));
1841
						}
1842
						$data .= ')';
1843
					} else {
1844
						$ret = $this->conditionKeysToString($value, $quoteValues, $model);
1845
						if (count($ret) > 1) {
1846
							$data = '(' . join(') AND (', $ret) . ')';
1847
						} elseif (isset($ret[0])) {
1848
							$data = $ret[0];
1849
						}
1850
					}
1851
				} elseif (is_numeric($key) && !empty($value)) {
1852
					$data = $this->__quoteFields($value);
1853
				} else {
1854
					$data = $this->__parseKey($model, trim($key), $value);
1855
				}
1856
 
1857
				if ($data != null) {
1858
					if (preg_match('/^\(\(\((.+)\)\)\)$/', $data)) {
1859
						$data = substr($data, 1, strlen($data) - 2);
1860
					}
1861
					$out[] = $data;
1862
					$data = null;
1863
				}
1864
			}
1865
			$c++;
1866
		}
1867
		return $out;
1868
	}
1869
/**
1870
 * Extracts a Model.field identifier and an SQL condition operator from a string, formats
1871
 * and inserts values, and composes them into an SQL snippet.
1872
 *
1873
 * @param Model $model Model object initiating the query
1874
 * @param string $key An SQL key snippet containing a field and optional SQL operator
1875
 * @param mixed $value The value(s) to be inserted in the string
1876
 * @return string
1877
 * @access private
1878
 */
1879
	function __parseKey($model, $key, $value) {
1880
		$operatorMatch = '/^((' . join(')|(', $this->__sqlOps);
1881
		$operatorMatch .= '\\x20)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is';
1882
		$bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false));
1883
 
1884
		if (!strpos($key, ' ')) {
1885
			$operator = '=';
1886
		} else {
1887
			list($key, $operator) = explode(' ', trim($key), 2);
1888
 
1889
			if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) {
1890
				$key = $key . ' ' . $operator;
1891
				$split = strrpos($key, ' ');
1892
				$operator = substr($key, $split);
1893
				$key = substr($key, 0, $split);
1894
			}
1895
		}
1896
		$type = (is_object($model) ? $model->getColumnType($key) : null);
1897
		$null = ($value === null || (is_array($value) && empty($value)));
1898
 
1899
		if (strtolower($operator) === 'not') {
1900
			$data = $this->conditionKeysToString(
1901
				array($operator => array($key => $value)), true, $model
1902
			);
1903
			return $data[0];
1904
		}
1905
		$value = $this->value($value, $type);
1906
 
1907
		$key = (strpos($key, '(') !== false || strpos($key, ')') !== false) ?
1908
			$this->__quoteFields($key) :
1909
			$key = $this->name($key);
1910
 
1911
		if ($bound) {
1912
			return String::insert($key . ' ' . trim($operator), $value);
1913
		}
1914
 
1915
		if (!preg_match($operatorMatch, trim($operator))) {
1916
			$operator .= ' =';
1917
		}
1918
		$operator = trim($operator);
1919
 
1920
		if (is_array($value)) {
1921
			$value = join(', ', $value);
1922
 
1923
			switch ($operator) {
1924
				case '=':
1925
					$operator = 'IN';
1926
				break;
1927
				case '!=':
1928
				case '<>':
1929
					$operator = 'NOT IN';
1930
				break;
1931
			}
1932
			$value = "({$value})";
1933
		} elseif ($null) {
1934
			switch ($operator) {
1935
				case '=':
1936
					$operator = 'IS';
1937
				break;
1938
				case '!=':
1939
				case '<>':
1940
					$operator = 'IS NOT';
1941
				break;
1942
			}
1943
		}
1944
		return "{$key} {$operator} {$value}";
1945
	}
1946
/**
1947
 * Quotes Model.fields
1948
 *
1949
 * @param string $conditions
1950
 * @return string or false if no match
1951
 * @access private
1952
 */
1953
	function __quoteFields($conditions) {
1954
		$start = $end  = null;
1955
		$original = $conditions;
1956
 
1957
		if (!empty($this->startQuote)) {
1958
			$start = preg_quote($this->startQuote);
1959
		}
1960
		if (!empty($this->endQuote)) {
1961
			$end = preg_quote($this->endQuote);
1962
		}
1963
		$conditions = str_replace(array($start, $end), '', $conditions);
1964
		preg_match_all('/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_' . $start . $end . ']*\\.[a-z0-9_' . $start . $end . ']*)/i', $conditions, $replace, PREG_PATTERN_ORDER);
1965
 
1966
		if (isset($replace['1']['0'])) {
1967
			$pregCount = count($replace['1']);
1968
 
1969
			for ($i = 0; $i < $pregCount; $i++) {
1970
				if (!empty($replace['1'][$i]) && !is_numeric($replace['1'][$i])) {
1971
					$conditions = preg_replace('/\b' . preg_quote($replace['1'][$i]) . '\b/', $this->name($replace['1'][$i]), $conditions);
1972
				}
1973
			}
1974
			return $conditions;
1975
		}
1976
		return $original;
1977
	}
1978
/**
1979
 * Returns a limit statement in the correct format for the particular database.
1980
 *
1981
 * @param integer $limit Limit of results returned
1982
 * @param integer $offset Offset from which to start results
1983
 * @return string SQL limit/offset statement
1984
 */
1985
	function limit($limit, $offset = null) {
1986
		if ($limit) {
1987
			$rt = '';
1988
			if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
1989
				$rt = ' LIMIT';
1990
			}
1991
 
1992
			if ($offset) {
1993
				$rt .= ' ' . $offset . ',';
1994
			}
1995
 
1996
			$rt .= ' ' . $limit;
1997
			return $rt;
1998
		}
1999
		return null;
2000
	}
2001
/**
2002
 * Returns an ORDER BY clause as a string.
2003
 *
2004
 * @param string $key Field reference, as a key (i.e. Post.title)
2005
 * @param string $direction Direction (ASC or DESC)
2006
 * @return string ORDER BY clause
2007
 */
2008
	function order($keys, $direction = 'ASC') {
2009
		if (is_string($keys) && strpos($keys, ',') && !preg_match('/\(.+\,.+\)/', $keys)) {
2010
			$keys = array_map('trim', explode(',', $keys));
2011
		}
2012
 
2013
		if (is_array($keys)) {
2014
			$keys = array_filter($keys);
2015
		}
2016
 
2017
		if (empty($keys) || (is_array($keys) && count($keys) && isset($keys[0]) && empty($keys[0]))) {
2018
			return '';
2019
		}
2020
 
2021
		if (is_array($keys)) {
2022
			$keys = (Set::countDim($keys) > 1) ? array_map(array(&$this, 'order'), $keys) : $keys;
2023
 
2024
			foreach ($keys as $key => $value) {
2025
				if (is_numeric($key)) {
2026
					$key = $value = ltrim(str_replace('ORDER BY ', '', $this->order($value)));
2027
					$value = (!preg_match('/\\x20ASC|\\x20DESC/i', $key) ? ' ' . $direction : '');
2028
				} else {
2029
					$value = ' ' . $value;
2030
				}
2031
 
2032
				if (!preg_match('/^.+\\(.*\\)/', $key) && !strpos($key, ',')) {
2033
					if (preg_match('/\\x20ASC|\\x20DESC/i', $key, $dir)) {
2034
						$dir = $dir[0];
2035
						$key = preg_replace('/\\x20ASC|\\x20DESC/i', '', $key);
2036
					} else {
2037
						$dir = '';
2038
					}
2039
					$key = trim($key);
2040
					if (!preg_match('/\s/', $key)) {
2041
						$key = $this->name($key);
2042
					}
2043
					$key .= ' ' . trim($dir);
2044
				}
2045
				$order[] = $this->order($key . $value);
2046
			}
2047
			return ' ORDER BY ' . trim(str_replace('ORDER BY', '', join(',', $order)));
2048
		}
2049
		$keys = preg_replace('/ORDER\\x20BY/i', '', $keys);
2050
 
2051
		if (strpos($keys, '.')) {
2052
			preg_match_all('/([a-zA-Z0-9_]{1,})\\.([a-zA-Z0-9_]{1,})/', $keys, $result, PREG_PATTERN_ORDER);
2053
			$pregCount = count($result[0]);
2054
 
2055
			for ($i = 0; $i < $pregCount; $i++) {
2056
				if (!is_numeric($result[0][$i])) {
2057
					$keys = preg_replace('/' . $result[0][$i] . '/', $this->name($result[0][$i]), $keys);
2058
				}
2059
			}
2060
			$result = ' ORDER BY ' . $keys;
2061
			return $result . (!preg_match('/\\x20ASC|\\x20DESC/i', $keys) ? ' ' . $direction : '');
2062
 
2063
		} elseif (preg_match('/(\\x20ASC|\\x20DESC)/i', $keys, $match)) {
2064
			$direction = $match[1];
2065
			return ' ORDER BY ' . preg_replace('/' . $match[1] . '/', '', $keys) . $direction;
2066
		}
2067
		return ' ORDER BY ' . $keys . ' ' . $direction;
2068
	}
2069
/**
2070
 * Create a GROUP BY SQL clause
2071
 *
2072
 * @param string $group Group By Condition
2073
 * @return mixed string condition or null
2074
 */
2075
	function group($group) {
2076
		if ($group) {
2077
			if (is_array($group)) {
2078
				$group = join(', ', $group);
2079
			}
2080
			return ' GROUP BY ' . $this->__quoteFields($group);
2081
		}
2082
		return null;
2083
	}
2084
/**
2085
 * Disconnects database, kills the connection and says the connection is closed,
2086
 * and if DEBUG is turned on, the log for this object is shown.
2087
 *
2088
 */
2089
	function close() {
2090
		if (Configure::read() > 1) {
2091
			$this->showLog();
2092
		}
2093
		$this->disconnect();
2094
	}
2095
/**
2096
 * Checks if the specified table contains any record matching specified SQL
2097
 *
2098
 * @param Model $model Model to search
2099
 * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
2100
 * @return boolean True if the table has a matching record, else false
2101
 */
2102
	function hasAny(&$Model, $sql) {
2103
		$sql = $this->conditions($sql);
2104
		$table = $this->fullTableName($Model);
2105
		$where = $sql ? "WHERE {$sql}" : 'WHERE 1 = 1';
2106
		$id = $Model->primaryKey;
2107
 
2108
		$out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$where}");
2109
 
2110
		if (is_array($out)) {
2111
			return $out[0]['count'];
2112
		}
2113
		return false;
2114
	}
2115
/**
2116
 * Gets the length of a database-native column description, or null if no length
2117
 *
2118
 * @param string $real Real database-layer column type (i.e. "varchar(255)")
2119
 * @return mixed An integer or string representing the length of the column
2120
 */
2121
	function length($real) {
2122
		if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) {
2123
			trigger_error(__('FIXME: Can\'t parse field: ' . $real, true), E_USER_WARNING);
2124
			$col = str_replace(array(')', 'unsigned'), '', $real);
2125
			$limit = null;
2126
 
2127
			if (strpos($col, '(') !== false) {
2128
				list($col, $limit) = explode('(', $col);
2129
			}
2130
			if ($limit != null) {
2131
				return intval($limit);
2132
			}
2133
			return null;
2134
		}
2135
 
2136
		$types = array(
2137
			'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1
2138
		);
2139
 
2140
		list($real, $type, $length, $offset, $sign, $zerofill) = $result;
2141
		$typeArr = $type;
2142
		$type = $type[0];
2143
		$length = $length[0];
2144
		$offset = $offset[0];
2145
 
2146
		$isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double'));
2147
		if ($isFloat && $offset) {
2148
			return $length.','.$offset;
2149
		}
2150
 
2151
		if (($real[0] == $type) && (count($real) == 1)) {
2152
			return null;
2153
		}
2154
 
2155
		if (isset($types[$type])) {
2156
			$length += $types[$type];
2157
			if (!empty($sign)) {
2158
				$length--;
2159
			}
2160
		} elseif (in_array($type, array('enum', 'set'))) {
2161
			$length = 0;
2162
			foreach ($typeArr as $key => $enumValue) {
2163
				if ($key == 0) {
2164
					continue;
2165
				}
2166
				$tmpLength = strlen($enumValue);
2167
				if ($tmpLength > $length) {
2168
					$length = $tmpLength;
2169
				}
2170
			}
2171
		}
2172
		return intval($length);
2173
	}
2174
/**
2175
 * Translates between PHP boolean values and Database (faked) boolean values
2176
 *
2177
 * @param mixed $data Value to be translated
2178
 * @return mixed Converted boolean value
2179
 */
2180
	function boolean($data) {
2181
		if ($data === true || $data === false) {
2182
			if ($data === true) {
2183
				return 1;
2184
			}
2185
			return 0;
2186
		} else {
2187
			return !empty($data);
2188
		}
2189
	}
2190
/**
2191
 * Inserts multiple values into a table
2192
 *
2193
 * @param string $table
2194
 * @param string $fields
2195
 * @param array $values
2196
 * @access protected
2197
 */
2198
	function insertMulti($table, $fields, $values) {
2199
		$table = $this->fullTableName($table);
2200
		if (is_array($fields)) {
2201
			$fields = join(', ', array_map(array(&$this, 'name'), $fields));
2202
		}
2203
		$count = count($values);
2204
		for ($x = 0; $x < $count; $x++) {
2205
			$this->query("INSERT INTO {$table} ({$fields}) VALUES {$values[$x]}");
2206
		}
2207
	}
2208
/**
2209
 * Returns an array of the indexes in given datasource name.
2210
 *
2211
 * @param string $model Name of model to inspect
2212
 * @return array Fields in table. Keys are column and unique
2213
 */
2214
	function index($model) {
2215
		return false;
2216
	}
2217
/**
2218
 * Generate a database-native schema for the given Schema object
2219
 *
2220
 * @param object $schema An instance of a subclass of CakeSchema
2221
 * @param string $tableName Optional.  If specified only the table name given will be generated.
2222
 *						Otherwise, all tables defined in the schema are generated.
2223
 * @return string
2224
 */
2225
	function createSchema($schema, $tableName = null) {
2226
		if (!is_a($schema, 'CakeSchema')) {
2227
			trigger_error(__('Invalid schema object', true), E_USER_WARNING);
2228
			return null;
2229
		}
2230
		$out = '';
2231
 
2232
		foreach ($schema->tables as $curTable => $columns) {
2233
			if (!$tableName || $tableName == $curTable) {
2234
				$cols = $colList = $indexes = array();
2235
				$primary = null;
2236
				$table = $this->fullTableName($curTable);
2237
 
2238
				foreach ($columns as $name => $col) {
2239
					if (is_string($col)) {
2240
						$col = array('type' => $col);
2241
					}
2242
					if (isset($col['key']) && $col['key'] == 'primary') {
2243
						$primary = $name;
2244
					}
2245
					if ($name !== 'indexes') {
2246
						$col['name'] = $name;
2247
						if (!isset($col['type'])) {
2248
							$col['type'] = 'string';
2249
						}
2250
						$cols[] = $this->buildColumn($col);
2251
					} else {
2252
						$indexes = array_merge($indexes, $this->buildIndex($col, $table));
2253
					}
2254
				}
2255
				if (empty($indexes) && !empty($primary)) {
2256
					$col = array('PRIMARY' => array('column' => $primary, 'unique' => 1));
2257
					$indexes = array_merge($indexes, $this->buildIndex($col, $table));
2258
				}
2259
				$columns = $cols;
2260
				$out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes')) . "\n\n";
2261
			}
2262
		}
2263
		return $out;
2264
	}
2265
/**
2266
 * Generate a alter syntax from	 CakeSchema::compare()
2267
 *
2268
 * @param unknown_type $schema
2269
 * @return unknown
2270
 */
2271
	function alterSchema($compare, $table = null) {
2272
		return false;
2273
	}
2274
/**
2275
 * Generate a "drop table" statement for the given Schema object
2276
 *
2277
 * @param object $schema An instance of a subclass of CakeSchema
2278
 * @param string $table Optional.  If specified only the table name given will be generated.
2279
 *						Otherwise, all tables defined in the schema are generated.
2280
 * @return string
2281
 */
2282
	function dropSchema($schema, $table = null) {
2283
		if (!is_a($schema, 'CakeSchema')) {
2284
			trigger_error(__('Invalid schema object', true), E_USER_WARNING);
2285
			return null;
2286
		}
2287
		$out = '';
2288
 
2289
		foreach ($schema->tables as $curTable => $columns) {
2290
			if (!$table || $table == $curTable) {
2291
				$out .= 'DROP TABLE ' . $this->fullTableName($curTable) . ";\n";
2292
			}
2293
		}
2294
		return $out;
2295
	}
2296
/**
2297
 * Generate a database-native column schema string
2298
 *
2299
 * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
2300
 *						where options can be 'default', 'length', or 'key'.
2301
 * @return string
2302
 */
2303
	function buildColumn($column) {
2304
		$name = $type = null;
2305
		extract(array_merge(array('null' => true), $column));
2306
 
2307
		if (empty($name) || empty($type)) {
2308
			trigger_error('Column name or type not defined in schema', E_USER_WARNING);
2309
			return null;
2310
		}
2311
 
2312
		if (!isset($this->columns[$type])) {
2313
			trigger_error("Column type {$type} does not exist", E_USER_WARNING);
2314
			return null;
2315
		}
2316
 
2317
		$real = $this->columns[$type];
2318
		$out = $this->name($name) . ' ' . $real['name'];
2319
 
2320
		if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
2321
			if (isset($column['length'])) {
2322
				$length = $column['length'];
2323
			} elseif (isset($column['limit'])) {
2324
				$length = $column['limit'];
2325
			} elseif (isset($real['length'])) {
2326
				$length = $real['length'];
2327
			} else {
2328
				$length = $real['limit'];
2329
			}
2330
			$out .= '(' . $length . ')';
2331
		}
2332
 
2333
		if (($column['type'] == 'integer' || $column['type'] == 'float' ) && isset($column['default']) && $column['default'] === '') {
2334
			$column['default'] = null;
2335
		}
2336
 
2337
		if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
2338
			$out .= ' ' . $this->columns['primary_key']['name'];
2339
		} elseif (isset($column['key']) && $column['key'] == 'primary') {
2340
			$out .= ' NOT NULL';
2341
		} elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
2342
			$out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
2343
		} elseif (isset($column['default'])) {
2344
			$out .= ' DEFAULT ' . $this->value($column['default'], $type);
2345
		} elseif (isset($column['null']) && $column['null'] == true) {
2346
			$out .= ' DEFAULT NULL';
2347
		} elseif (isset($column['null']) && $column['null'] == false) {
2348
			$out .= ' NOT NULL';
2349
		}
2350
		return $out;
2351
	}
2352
/**
2353
 * Format indexes for create table
2354
 *
2355
 * @param array $indexes
2356
 * @param string $table
2357
 * @return array
2358
 */
2359
	function buildIndex($indexes, $table = null) {
2360
		$join = array();
2361
		foreach ($indexes as $name => $value) {
2362
			$out = '';
2363
			if ($name == 'PRIMARY') {
2364
				$out .= 'PRIMARY ';
2365
				$name = null;
2366
			} else {
2367
				if (!empty($value['unique'])) {
2368
					$out .= 'UNIQUE ';
2369
				}
2370
			}
2371
			if (is_array($value['column'])) {
2372
				$out .= 'KEY '. $name .' (' . join(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
2373
			} else {
2374
				$out .= 'KEY '. $name .' (' . $this->name($value['column']) . ')';
2375
			}
2376
			$join[] = $out;
2377
		}
2378
		return $join;
2379
	}
2380
/**
2381
 * Guesses the data type of an array
2382
 *
2383
 * @param string $value
2384
 * @return void
2385
 * @access public
2386
 */
2387
	function introspectType($value) {
2388
		if (!is_array($value)) {
2389
			if ($value === true || $value === false) {
2390
				return 'boolean';
2391
			}
2392
			if (is_float($value) && floatval($value) === $value) {
2393
				return 'float';
2394
			}
2395
			if (is_int($value) && intval($value) === $value) {
2396
				return 'integer';
2397
			}
2398
			if (is_string($value) && strlen($value) > 255) {
2399
				return 'text';
2400
			}
2401
			return 'string';
2402
		}
2403
 
2404
		$isAllFloat = $isAllInt = true;
2405
		$containsFloat = $containsInt = $containsString = false;
2406
		foreach ($value as $key => $valElement) {
2407
			$valElement = trim($valElement);
2408
			if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) {
2409
				$isAllFloat = false;
2410
			} else {
2411
				$containsFloat = true;
2412
				continue;
2413
			}
2414
			if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) {
2415
				$isAllInt = false;
2416
			} else {
2417
				$containsInt = true;
2418
				continue;
2419
			}
2420
			$containsString = true;
2421
		}
2422
 
2423
		if ($isAllFloat) {
2424
			return 'float';
2425
		}
2426
		if ($isAllInt) {
2427
			return 'integer';
2428
		}
2429
 
2430
		if ($containsInt && !$containsString) {
2431
			return 'integer';
2432
		}
2433
		return 'string';
2434
	}
2435
}
2436
?>