QueryBuilder.php 28.8 KB
Newer Older
1 2 3 4 5 6 7 8
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\sphinx;
9 10 11

use yii\base\Object;
use yii\db\Exception;
12
use yii\db\Expression;
13 14

/**
15 16 17 18
 * QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object.
 *
 * QueryBuilder can also be used to build SQL statements such as INSERT, REPLACE, UPDATE, DELETE,
 * from a [[Query]] object.
19 20 21 22
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
23
class QueryBuilder extends Object
24
{
25 26 27
	/**
	 * The prefix for automatically generated query binding parameters.
	 */
28
	const PARAM_PREFIX = ':qp';
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

	/**
	 * @var Connection the Sphinx connection.
	 */
	public $db;
	/**
	 * @var string the separator between different fragments of a SQL statement.
	 * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement.
	 */
	public $separator = " ";

	/**
	 * Constructor.
	 * @param Connection $connection the Sphinx connection.
	 * @param array $config name-value pairs that will be used to initialize the object properties
	 */
	public function __construct($connection, $config = [])
	{
		$this->db = $connection;
		parent::__construct($config);
	}

51 52 53 54 55 56 57 58 59
	/**
	 * Generates a SELECT SQL statement from a [[Query]] object.
	 * @param Query $query the [[Query]] object from which the SQL statement will be generated
	 * @return array the generated SQL statement (the first array element) and the corresponding
	 * parameters to be bound to the SQL statement (the second array element).
	 */
	public function build($query)
	{
		$params = $query->params;
60 61 62 63 64
		if ($query->match !== null) {
			$phName = self::PARAM_PREFIX . count($params);
			$params[$phName] = (string)$query->match;
			$query->andWhere('MATCH(' . $phName . ')');
		}
65 66 67
		$clauses = [
			$this->buildSelect($query->select, $query->distinct, $query->selectOption),
			$this->buildFrom($query->from),
68
			$this->buildWhere($query->from, $query->where, $params),
69 70 71 72
			$this->buildGroupBy($query->groupBy),
			$this->buildWithin($query->within),
			$this->buildOrderBy($query->orderBy),
			$this->buildLimit($query->limit, $query->offset),
73
			$this->buildOption($query->options, $params),
74 75 76 77 78
		];
		return [implode($this->separator, array_filter($clauses)), $params];
	}

	/**
79 80 81 82 83 84 85
	 * Creates an INSERT SQL statement.
	 * For example,
	 *
	 * ~~~
	 * $sql = $queryBuilder->insert('idx_user', [
	 *	 'name' => 'Sam',
	 *	 'age' => 30,
86
	 *	 'id' => 10,
87 88 89 90 91 92 93 94
	 * ], $params);
	 * ~~~
	 *
	 * The method will properly escape the index and column names.
	 *
	 * @param string $index the index that new rows will be inserted into.
	 * @param array $columns the column data (name => value) to be inserted into the index.
	 * @param array $params the binding parameters that will be generated by this method.
95
	 * They should be bound to the Sphinx command later.
96
	 * @return string the INSERT SQL
97
	 */
98
	public function insert($index, $columns, &$params)
99 100 101 102 103 104 105 106 107 108 109 110
	{
		return $this->generateInsertReplace('INSERT', $index, $columns, $params);
	}

	/**
	 * Creates an REPLACE SQL statement.
	 * For example,
	 *
	 * ~~~
	 * $sql = $queryBuilder->replace('idx_user', [
	 *	 'name' => 'Sam',
	 *	 'age' => 30,
111
	 *	 'id' => 10,
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
	 * ], $params);
	 * ~~~
	 *
	 * The method will properly escape the index and column names.
	 *
	 * @param string $index the index that new rows will be replaced.
	 * @param array $columns the column data (name => value) to be replaced in the index.
	 * @param array $params the binding parameters that will be generated by this method.
	 * They should be bound to the Sphinx command later.
	 * @return string the INSERT SQL
	 */
	public function replace($index, $columns, &$params)
	{
		return $this->generateInsertReplace('REPLACE', $index, $columns, $params);
	}

	/**
	 * Generates INSERT/REPLACE SQL statement.
	 * @param string $statement statement ot be generated.
	 * @param string $index the affected index name.
	 * @param array $columns the column data (name => value).
	 * @param array $params the binding parameters that will be generated by this method.
	 * @return string generated SQL
	 */
	protected function generateInsertReplace($statement, $index, $columns, &$params)
137
	{
138
		if (($indexSchema = $this->db->getIndexSchema($index)) !== null) {
139
			$indexSchemas = [$indexSchema];
140
		} else {
141
			$indexSchemas = [];
142
		}
143 144 145 146
		$names = [];
		$placeholders = [];
		foreach ($columns as $name => $value) {
			$names[] = $this->db->quoteColumnName($name);
147
			$placeholders[] = $this->composeColumnValue($indexSchemas, $name, $value, $params);
148
		}
149
		return $statement . ' INTO ' . $this->db->quoteIndexName($index)
150 151
			. ' (' . implode(', ', $names) . ') VALUES ('
			. implode(', ', $placeholders) . ')';
152 153 154
	}

	/**
155 156 157 158
	 * Generates a batch INSERT SQL statement.
	 * For example,
	 *
	 * ~~~
159 160 161 162
	 * $connection->createCommand()->batchInsert('idx_user', ['id', 'name', 'age'], [
	 *     [1, 'Tom', 30],
	 *     [2, 'Jane', 20],
	 *     [3, 'Linda', 25],
163 164 165 166 167 168 169 170
	 * ])->execute();
	 * ~~~
	 *
	 * Note that the values in each row must match the corresponding column names.
	 *
	 * @param string $index the index that new rows will be inserted into.
	 * @param array $columns the column names
	 * @param array $rows the rows to be batch inserted into the index
171
	 * @param array $params the binding parameters that will be generated by this method.
172
	 * They should be bound to the Sphinx command later.
173
	 * @return string the batch INSERT SQL statement
174
	 */
175
	public function batchInsert($index, $columns, $rows, &$params)
176 177 178 179 180 181 182 183 184
	{
		return $this->generateBatchInsertReplace('INSERT', $index, $columns, $rows, $params);
	}

	/**
	 * Generates a batch REPLACE SQL statement.
	 * For example,
	 *
	 * ~~~
185 186 187 188
	 * $connection->createCommand()->batchReplace('idx_user', ['id', 'name', 'age'], [
	 *     [1, 'Tom', 30],
	 *     [2, 'Jane', 20],
	 *     [3, 'Linda', 25],
189 190 191 192 193 194 195 196 197
	 * ])->execute();
	 * ~~~
	 *
	 * Note that the values in each row must match the corresponding column names.
	 *
	 * @param string $index the index that new rows will be replaced.
	 * @param array $columns the column names
	 * @param array $rows the rows to be batch replaced in the index
	 * @param array $params the binding parameters that will be generated by this method.
198
	 * They should be bound to the Sphinx command later.
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
	 * @return string the batch INSERT SQL statement
	 */
	public function batchReplace($index, $columns, $rows, &$params)
	{
		return $this->generateBatchInsertReplace('REPLACE', $index, $columns, $rows, $params);
	}

	/**
	 * Generates a batch INSERT/REPLACE SQL statement.
	 * @param string $statement statement ot be generated.
	 * @param string $index the affected index name.
	 * @param array $columns the column data (name => value).
	 * @param array $rows the rows to be batch inserted into the index
	 * @param array $params the binding parameters that will be generated by this method.
	 * @return string generated SQL
	 */
	protected function generateBatchInsertReplace($statement, $index, $columns, $rows, &$params)
216
	{
217
		if (($indexSchema = $this->db->getIndexSchema($index)) !== null) {
218
			$indexSchemas = [$indexSchema];
219
		} else {
220
			$indexSchemas = [];
221
		}
222 223 224

		foreach ($columns as $i => $name) {
			$columns[$i] = $this->db->quoteColumnName($name);
225
		}
226 227 228 229 230

		$values = [];
		foreach ($rows as $row) {
			$vs = [];
			foreach ($row as $i => $value) {
231
				$vs[] = $this->composeColumnValue($indexSchemas, $columns[$i], $value, $params);
232 233 234 235
			}
			$values[] = '(' . implode(', ', $vs) . ')';
		}

236
		return $statement . ' INTO ' . $this->db->quoteIndexName($index)
237
			. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
238
	}
239 240

	/**
241
	 * Creates an UPDATE SQL statement.
242 243 244
	 * For example,
	 *
	 * ~~~
245 246
	 * $params = [];
	 * $sql = $queryBuilder->update('idx_user', ['status' => 1], 'age > 30', $params);
247 248
	 * ~~~
	 *
249
	 * The method will properly escape the index and column names.
250
	 *
251 252 253 254 255
	 * @param string $index the index to be updated.
	 * @param array $columns the column data (name => value) to be updated.
	 * @param array|string $condition the condition that will be put in the WHERE part. Please
	 * refer to [[Query::where()]] on how to specify condition.
	 * @param array $params the binding parameters that will be modified by this method
256
	 * so that they can be bound to the Sphinx command later.
257
	 * @param array $options list of options in format: optionName => optionValue
258
	 * @return string the UPDATE SQL
259
	 */
260
	public function update($index, $columns, $condition, &$params, $options)
261
	{
262
		if (($indexSchema = $this->db->getIndexSchema($index)) !== null) {
263
			$indexSchemas = [$indexSchema];
264
		} else {
265
			$indexSchemas = [];
266
		}
267 268

		$lines = [];
269
		foreach ($columns as $name => $value) {
270
			$lines[] = $this->db->quoteColumnName($name) . '=' . $this->composeColumnValue($indexSchemas, $name, $value, $params);
271 272
		}

273
		$sql = 'UPDATE ' . $this->db->quoteIndexName($index) . ' SET ' . implode(', ', $lines);
274
		$where = $this->buildWhere([$index], $condition, $params);
275 276 277 278 279 280 281 282
		if ($where !== '') {
			$sql = $sql . ' ' . $where;
		}
		$option = $this->buildOption($options, $params);
		if ($option !== '') {
			$sql = $sql . ' ' . $option;
		}
		return $sql;
283 284 285 286 287 288 289
	}

	/**
	 * Creates a DELETE SQL statement.
	 * For example,
	 *
	 * ~~~
290
	 * $sql = $queryBuilder->delete('idx_user', 'status = 0');
291 292 293 294 295 296 297 298
	 * ~~~
	 *
	 * The method will properly escape the index and column names.
	 *
	 * @param string $index the index where the data will be deleted from.
	 * @param array|string $condition the condition that will be put in the WHERE part. Please
	 * refer to [[Query::where()]] on how to specify condition.
	 * @param array $params the binding parameters that will be modified by this method
299
	 * so that they can be bound to the Sphinx command later.
300 301 302 303 304
	 * @return string the DELETE SQL
	 */
	public function delete($index, $condition, &$params)
	{
		$sql = 'DELETE FROM ' . $this->db->quoteIndexName($index);
305
		$where = $this->buildWhere([$index], $condition, $params);
306 307 308 309
		return $where === '' ? $sql : $sql . ' ' . $where;
	}

	/**
310
	 * Builds a SQL statement for truncating an index.
311
	 * @param string $index the index to be truncated. The name will be properly quoted by the method.
312
	 * @return string the SQL statement for truncating an index.
313 314 315 316 317 318
	 */
	public function truncateIndex($index)
	{
		return 'TRUNCATE RTINDEX ' . $this->db->quoteIndexName($index);
	}

319 320 321 322 323
	/**
	 * Builds a SQL statement for call snippet from provided data and query, using specified index settings.
	 * @param string $index name of the index, from which to take the text processing settings.
	 * @param string|array $source is the source data to extract a snippet from.
	 * It could be either a single string or array of strings.
324
	 * @param string $match the full-text query to build snippets for.
325 326 327 328 329
	 * @param array $options list of options in format: optionName => optionValue
	 * @param array $params the binding parameters that will be modified by this method
	 * so that they can be bound to the Sphinx command later.
	 * @return string the SQL statement for call snippets.
	 */
330
	public function callSnippets($index, $source, $match, $options, &$params)
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	{
		if (is_array($source)) {
			$dataSqlParts = [];
			foreach ($source as $sourceRow) {
				$phName = self::PARAM_PREFIX . count($params);
				$params[$phName] = $sourceRow;
				$dataSqlParts[] = $phName;
			}
			$dataSql = '(' . implode(',', $dataSqlParts) . ')';
		} else {
			$phName = self::PARAM_PREFIX . count($params);
			$params[$phName] = $source;
			$dataSql = $phName;
		}
		$indexParamName = self::PARAM_PREFIX . count($params);
		$params[$indexParamName] = $index;
347 348
		$matchParamName = self::PARAM_PREFIX . count($params);
		$params[$matchParamName] = $match;
349 350 351
		if (!empty($options)) {
			$optionParts = [];
			foreach ($options as $name => $value) {
352 353 354 355 356 357 358
				if ($value instanceof Expression) {
					$actualValue = $value->expression;
				} else {
					$actualValue = self::PARAM_PREFIX . count($params);
					$params[$actualValue] = $value;
				}
				$optionParts[] = $actualValue . ' AS ' . $name;
359 360 361 362 363
			}
			$optionSql = ', ' . implode(', ', $optionParts);
		} else {
			$optionSql = '';
		}
364
		return 'CALL SNIPPETS(' . $dataSql. ', ' . $indexParamName . ', ' . $matchParamName . $optionSql. ')';
365 366
	}

367 368 369 370 371 372 373 374 375 376
	/**
	 * Builds a SQL statement for returning tokenized and normalized forms of the keywords, and,
	 * optionally, keyword statistics.
	 * @param string $index the name of the index from which to take the text processing settings
	 * @param string $text the text to break down to keywords.
	 * @param boolean $fetchStatistic whether to return document and hit occurrence statistics
	 * @param array $params the binding parameters that will be modified by this method
	 * so that they can be bound to the Sphinx command later.
	 * @return string the SQL statement for call keywords.
	 */
377 378 379 380 381 382 383 384 385
	public function callKeywords($index, $text, $fetchStatistic, &$params)
	{
		$indexParamName = self::PARAM_PREFIX . count($params);
		$params[$indexParamName] = $index;
		$textParamName = self::PARAM_PREFIX . count($params);
		$params[$textParamName] = $text;
		return 'CALL KEYWORDS(' . $textParamName . ', ' . $indexParamName . ($fetchStatistic ? ', 1' : '') . ')';
	}

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
	/**
	 * @param array $columns
	 * @param boolean $distinct
	 * @param string $selectOption
	 * @return string the SELECT clause built from [[query]].
	 */
	public function buildSelect($columns, $distinct = false, $selectOption = null)
	{
		$select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
		if ($selectOption !== null) {
			$select .= ' ' . $selectOption;
		}

		if (empty($columns)) {
			return $select . ' *';
		}

		foreach ($columns as $i => $column) {
			if (is_object($column)) {
				$columns[$i] = (string)$column;
			} elseif (strpos($column, '(') === false) {
				if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
					$columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
				} else {
					$columns[$i] = $this->db->quoteColumnName($column);
				}
			}
		}

		if (is_array($columns)) {
			$columns = implode(', ', $columns);
		}

		return $select . ' ' . $columns;
	}

	/**
	 * @param array $indexes
	 * @return string the FROM clause built from [[query]].
	 */
	public function buildFrom($indexes)
	{
		if (empty($indexes)) {
			return '';
		}

		foreach ($indexes as $i => $index) {
			if (strpos($index, '(') === false) {
				if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $index, $matches)) { // with alias
					$indexes[$i] = $this->db->quoteIndexName($matches[1]) . ' ' . $this->db->quoteIndexName($matches[2]);
				} else {
					$indexes[$i] = $this->db->quoteIndexName($index);
				}
			}
		}

		if (is_array($indexes)) {
			$indexes = implode(', ', $indexes);
		}

		return 'FROM ' . $indexes;
	}

	/**
450
	 * @param string[] $indexes list of index names, which affected by query
451 452 453 454
	 * @param string|array $condition
	 * @param array $params the binding parameters to be populated
	 * @return string the WHERE clause built from [[query]].
	 */
455
	public function buildWhere($indexes, $condition, &$params)
456
	{
457 458 459 460 461 462 463 464 465 466 467 468 469
		if (empty($condition)) {
			return '';
		}
		$indexSchemas = [];
		if (!empty($indexes)) {
			foreach ($indexes as $indexName) {
				$index = $this->db->getIndexSchema($indexName);
				if ($index !== null) {
					$indexSchemas[] = $index;
				}
			}
		}
		$where = $this->buildCondition($indexSchemas, $condition, $params);
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
		return $where === '' ? '' : 'WHERE ' . $where;
	}

	/**
	 * @param array $columns
	 * @return string the GROUP BY clause
	 */
	public function buildGroupBy($columns)
	{
		return empty($columns) ? '' : 'GROUP BY ' . $this->buildColumns($columns);
	}

	/**
	 * @param array $columns
	 * @return string the ORDER BY clause built from [[query]].
	 */
	public function buildOrderBy($columns)
	{
		if (empty($columns)) {
			return '';
		}
		$orders = [];
		foreach ($columns as $name => $direction) {
			if (is_object($direction)) {
				$orders[] = (string)$direction;
			} else {
496
				$orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : 'ASC');
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
			}
		}

		return 'ORDER BY ' . implode(', ', $orders);
	}

	/**
	 * @param integer $limit
	 * @param integer $offset
	 * @return string the LIMIT and OFFSET clauses built from [[query]].
	 */
	public function buildLimit($limit, $offset)
	{
		$sql = '';
		if ($limit !== null && $limit >= 0) {
			$sql = 'LIMIT ' . (int)$limit;
		}
		if ($offset > 0) {
			$sql .= ' OFFSET ' . (int)$offset;
		}
		return ltrim($sql);
	}

	/**
	 * Processes columns and properly quote them if necessary.
	 * It will join all columns into a string with comma as separators.
	 * @param string|array $columns the columns to be processed
	 * @return string the processing result
	 */
	public function buildColumns($columns)
	{
		if (!is_array($columns)) {
			if (strpos($columns, '(') !== false) {
				return $columns;
			} else {
				$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
			}
		}
		foreach ($columns as $i => $column) {
			if (is_object($column)) {
				$columns[$i] = (string)$column;
			} elseif (strpos($column, '(') === false) {
				$columns[$i] = $this->db->quoteColumnName($column);
			}
		}
		return is_array($columns) ? implode(', ', $columns) : $columns;
	}

	/**
	 * Parses the condition specification and generates the corresponding SQL expression.
547
	 * @param IndexSchema[] $indexes list of indexes, which affected by query
548 549 550 551 552 553
	 * @param string|array $condition the condition specification. Please refer to [[Query::where()]]
	 * on how to specify a condition.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 * @throws \yii\db\Exception if the condition is in bad format
	 */
554
	public function buildCondition($indexes, $condition, &$params)
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
	{
		static $builders = [
			'AND' => 'buildAndCondition',
			'OR' => 'buildAndCondition',
			'BETWEEN' => 'buildBetweenCondition',
			'NOT BETWEEN' => 'buildBetweenCondition',
			'IN' => 'buildInCondition',
			'NOT IN' => 'buildInCondition',
			'LIKE' => 'buildLikeCondition',
			'NOT LIKE' => 'buildLikeCondition',
			'OR LIKE' => 'buildLikeCondition',
			'OR NOT LIKE' => 'buildLikeCondition',
		];

		if (!is_array($condition)) {
			return (string)$condition;
		} elseif (empty($condition)) {
			return '';
		}
		if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
			$operator = strtoupper($condition[0]);
			if (isset($builders[$operator])) {
				$method = $builders[$operator];
				array_shift($condition);
579
				return $this->$method($indexes, $operator, $condition, $params);
580 581 582 583
			} else {
				throw new Exception('Found unknown operator in query: ' . $operator);
			}
		} else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
584
			return $this->buildHashCondition($indexes, $condition, $params);
585 586 587 588 589
		}
	}

	/**
	 * Creates a condition based on column-value pairs.
590
	 * @param IndexSchema[] $indexes list of indexes, which affected by query
591 592 593 594
	 * @param array $condition the condition specification.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 */
595
	public function buildHashCondition($indexes, $condition, &$params)
596 597 598 599
	{
		$parts = [];
		foreach ($condition as $column => $value) {
			if (is_array($value)) { // IN condition
600
				$parts[] = $this->buildInCondition($indexes, 'IN', [$column, $value], $params);
601 602
			} else {
				if (strpos($column, '(') === false) {
603 604 605
					$quotedColumn = $this->db->quoteColumnName($column);
				} else {
					$quotedColumn = $column;
606 607
				}
				if ($value === null) {
608
					$parts[] = "$quotedColumn IS NULL";
609
				} else {
610
					$parts[] = $quotedColumn . '=' . $this->composeColumnValue($indexes, $column, $value, $params);
611 612 613 614 615 616 617 618
				}
			}
		}
		return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
	}

	/**
	 * Connects two or more SQL expressions with the `AND` or `OR` operator.
619
	 * @param IndexSchema[] $indexes list of indexes, which affected by query
620 621 622 623 624
	 * @param string $operator the operator to use for connecting the given operands
	 * @param array $operands the SQL expressions to connect.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 */
625
	public function buildAndCondition($indexes, $operator, $operands, &$params)
626 627 628 629
	{
		$parts = [];
		foreach ($operands as $operand) {
			if (is_array($operand)) {
630
				$operand = $this->buildCondition($indexes, $operand, $params);
631 632 633 634 635 636 637 638 639 640 641 642 643 644
			}
			if ($operand !== '') {
				$parts[] = $operand;
			}
		}
		if (!empty($parts)) {
			return '(' . implode(") $operator (", $parts) . ')';
		} else {
			return '';
		}
	}

	/**
	 * Creates an SQL expressions with the `BETWEEN` operator.
645
	 * @param IndexSchema[] $indexes list of indexes, which affected by query
646 647 648 649 650 651 652
	 * @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
	 * @param array $operands the first operand is the column name. The second and third operands
	 * describe the interval that column value should be in.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 * @throws Exception if wrong number of operands have been given.
	 */
653
	public function buildBetweenCondition($indexes, $operator, $operands, &$params)
654 655 656 657 658 659 660 661
	{
		if (!isset($operands[0], $operands[1], $operands[2])) {
			throw new Exception("Operator '$operator' requires three operands.");
		}

		list($column, $value1, $value2) = $operands;

		if (strpos($column, '(') === false) {
662 663 664
			$quotedColumn = $this->db->quoteColumnName($column);
		} else {
			$quotedColumn = $column;
665
		}
666 667
		$phName1 = $this->composeColumnValue($indexes, $column, $value1, $params);
		$phName2 = $this->composeColumnValue($indexes, $column, $value2, $params);
668

669
		return "$quotedColumn $operator $phName1 AND $phName2";
670 671 672 673
	}

	/**
	 * Creates an SQL expressions with the `IN` operator.
674
	 * @param IndexSchema[] $indexes list of indexes, which affected by query
675 676 677 678 679 680 681 682 683 684
	 * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
	 * @param array $operands the first operand is the column name. If it is an array
	 * a composite IN condition will be generated.
	 * The second operand is an array of values that column value should be among.
	 * If it is an empty array the generated expression will be a `false` value if
	 * operator is `IN` and empty if operator is `NOT IN`.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 * @throws Exception if wrong number of operands have been given.
	 */
685
	public function buildInCondition($indexes, $operator, $operands, &$params)
686 687 688 689 690 691 692 693 694 695 696 697 698 699
	{
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
		}

		list($column, $values) = $operands;

		$values = (array)$values;

		if (empty($values) || $column === []) {
			return $operator === 'IN' ? '0=1' : '';
		}

		if (count($column) > 1) {
700
			return $this->buildCompositeInCondition($indexes, $operator, $column, $values, $params);
701 702 703 704 705 706 707
		} elseif (is_array($column)) {
			$column = reset($column);
		}
		foreach ($values as $i => $value) {
			if (is_array($value)) {
				$value = isset($value[$column]) ? $value[$column] : null;
			}
708
			$values[$i] = $this->composeColumnValue($indexes, $column, $value, $params);
709 710 711 712 713 714 715 716 717 718 719 720 721
		}
		if (strpos($column, '(') === false) {
			$column = $this->db->quoteColumnName($column);
		}

		if (count($values) > 1) {
			return "$column $operator (" . implode(', ', $values) . ')';
		} else {
			$operator = $operator === 'IN' ? '=' : '<>';
			return "$column$operator{$values[0]}";
		}
	}

722 723 724 725 726 727 728 729 730
	/**
	 * @param IndexSchema[] $indexes list of indexes, which affected by query
	 * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
	 * @param array $columns
	 * @param array $values
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 */
	protected function buildCompositeInCondition($indexes, $operator, $columns, $values, &$params)
731 732 733 734 735 736
	{
		$vss = [];
		foreach ($values as $value) {
			$vs = [];
			foreach ($columns as $column) {
				if (isset($value[$column])) {
737
					$vs[] = $this->composeColumnValue($indexes, $column, $value[$column], $params);
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
				} else {
					$vs[] = 'NULL';
				}
			}
			$vss[] = '(' . implode(', ', $vs) . ')';
		}
		foreach ($columns as $i => $column) {
			if (strpos($column, '(') === false) {
				$columns[$i] = $this->db->quoteColumnName($column);
			}
		}
		return '(' . implode(', ', $columns) . ") $operator (" . implode(', ', $vss) . ')';
	}

	/**
	 * Creates an SQL expressions with the `LIKE` operator.
754
	 * @param IndexSchema[] $indexes list of indexes, which affected by query
755 756 757 758 759 760 761 762 763 764
	 * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
	 * @param array $operands the first operand is the column name.
	 * The second operand is a single value or an array of values that column value
	 * should be compared with.
	 * If it is an empty array the generated expression will be a `false` value if
	 * operator is `LIKE` or `OR LIKE` and empty if operator is `NOT LIKE` or `OR NOT LIKE`.
	 * @param array $params the binding parameters to be populated
	 * @return string the generated SQL expression
	 * @throws Exception if wrong number of operands have been given.
	 */
765
	public function buildLikeCondition($indexes, $operator, $operands, &$params)
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
	{
		if (!isset($operands[0], $operands[1])) {
			throw new Exception("Operator '$operator' requires two operands.");
		}

		list($column, $values) = $operands;

		$values = (array)$values;

		if (empty($values)) {
			return $operator === 'LIKE' || $operator === 'OR LIKE' ? '0=1' : '';
		}

		if ($operator === 'LIKE' || $operator === 'NOT LIKE') {
			$andor = ' AND ';
		} else {
			$andor = ' OR ';
			$operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE';
		}

		if (strpos($column, '(') === false) {
			$column = $this->db->quoteColumnName($column);
		}

		$parts = [];
		foreach ($values as $value) {
			$phName = self::PARAM_PREFIX . count($params);
			$params[$phName] = $value;
			$parts[] = "$column $operator $phName";
		}

		return implode($andor, $parts);
	}

	/**
	 * @param array $columns
	 * @return string the ORDER BY clause built from [[query]].
	 */
	public function buildWithin($columns)
	{
		if (empty($columns)) {
			return '';
		}
		$orders = [];
		foreach ($columns as $name => $direction) {
			if (is_object($direction)) {
				$orders[] = (string)$direction;
			} else {
Paul Klimov committed
814
				$orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
815 816 817 818 819 820
			}
		}
		return 'WITHIN GROUP ORDER BY ' . implode(', ', $orders);
	}

	/**
821 822
	 * @param array $options query options in format: optionName => optionValue
	 * @param array $params the binding parameters to be populated
823 824
	 * @return string the OPTION clause build from [[query]]
	 */
825
	public function buildOption($options, &$params)
826 827 828 829 830 831
	{
		if (empty($options)) {
			return '';
		}
		$optionLines = [];
		foreach ($options as $name => $value) {
832 833 834
			if ($value instanceof Expression) {
				$actualValue = $value->expression;
			} else {
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
				if (is_array($value)) {
					$actualValueParts = [];
					foreach ($value as $key => $valuePart) {
						if (is_numeric($key)) {
							$actualValuePart = '';
						} else {
							$actualValuePart = $key . ' = ';
						}
						if ($valuePart instanceof Expression) {
							$actualValuePart .= $valuePart->expression;
						} else {
							$phName = self::PARAM_PREFIX . count($params);
							$params[$phName] = $valuePart;
							$actualValuePart .= $phName;
						}
						$actualValueParts[] = $actualValuePart;
					}
					$actualValue = '(' . implode(', ', $actualValueParts) . ')';
				} else {
					$actualValue = self::PARAM_PREFIX . count($params);
					$params[$actualValue] = $value;
				}
857 858
			}
			$optionLines[] = $name . ' = ' . $actualValue;
859 860
		}
		return 'OPTION ' . implode(', ', $optionLines);
861
	}
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903

	/**
	 * Composes column value for SQL, taking in account the column type.
	 * @param IndexSchema[] $indexes list of indexes, which affected by query
	 * @param string $columnName name of the column
	 * @param mixed $value raw column value
	 * @param array $params the binding parameters to be populated
	 * @return string SQL expression, which represents column value
	 */
	protected function composeColumnValue($indexes, $columnName, $value, &$params) {
		if ($value === null) {
			return 'NULL';
		} elseif ($value instanceof Expression) {
			$params = array_merge($params, $value->params);
			return $value->expression;
		}
		foreach ($indexes as $index) {
			$columnSchema = $index->getColumn($columnName);
			if ($columnSchema !== null) {
				break;
			}
		}
		if (is_array($value)) {
			// MVA :
			$lineParts = [];
			foreach ($value as $subValue) {
				if ($subValue instanceof Expression) {
					$params = array_merge($params, $subValue->params);
					$lineParts[] = $subValue->expression;
				} else {
					$phName = self::PARAM_PREFIX . count($params);
					$lineParts[] = $phName;
					$params[$phName] = (isset($columnSchema)) ? $columnSchema->typecast($subValue) : $subValue;
				}
			}
			return '(' . implode(',', $lineParts) . ')';
		} else {
			$phName = self::PARAM_PREFIX . count($params);
			$params[$phName] = (isset($columnSchema)) ? $columnSchema->typecast($value) : $value;
			return $phName;
		}
	}
904
}