Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

914 lines
30 KiB

13 years ago
<?php
/**
* This file contains the Command class.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\db\dao;
13 years ago
use yii\db\Exception;
13 years ago
/**
13 years ago
* QueryBuilder builds a SELECT SQL statement based on the specification given as a [[BaseQuery]] object.
13 years ago
*
13 years ago
* QueryBuilder can also be used to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE,
13 years ago
* from a [[Query]] object.
*
13 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
13 years ago
class QueryBuilder extends \yii\base\Object
13 years ago
{
/**
13 years ago
* @var Connection the database connection.
*/
13 years ago
public $connection;
13 years ago
/**
13 years ago
* @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 = " ";
/**
13 years ago
* @var boolean whether to automatically quote table and column names when generating SQL statements.
*/
public $autoQuote = true;
13 years ago
/**
* @var array the abstract column types mapped to physical column types.
* This is mainly used to support creating/modifying tables using DB-independent data type specifications.
* Child classes should override this property to declare supported type mappings.
*/
public $typeMap = array();
/**
13 years ago
* @var Query the Query object that is currently being processed by the query builder to generate a SQL statement.
13 years ago
*/
public $query;
13 years ago
13 years ago
/**
* Constructor.
13 years ago
* @param Connection $connection the database connection.
13 years ago
*/
13 years ago
public function __construct($connection)
13 years ago
{
13 years ago
$this->connection = $connection;
13 years ago
}
13 years ago
/**
13 years ago
* Generates a SELECT SQL statement from a [[BaseQuery]] object.
* @param BaseQuery $query the [[Query]] object from which the SQL statement will be generated
13 years ago
* @return string the generated SQL statement
13 years ago
*/
13 years ago
public function build($query)
{
13 years ago
$clauses = array(
13 years ago
$this->buildSelect($query->select, $query->distinct, $query->selectOption),
$this->buildFrom($query->from),
$this->buildJoin($query->join),
$this->buildWhere($query->where),
$this->buildGroup($query->group),
13 years ago
$this->buildHaving($query->having),
$this->buildUnion($query->union),
$this->buildOrder($query->order),
13 years ago
$this->buildLimit($query->limit, $query->offset),
13 years ago
);
return implode($this->separator, array_filter($clauses));
13 years ago
}
/**
* Creates and executes an INSERT SQL statement.
* The method will properly escape the column names, and bind the values to be inserted.
13 years ago
* For example,
*
* ~~~
* $sql = $queryBuilder->insert('tbl_user', array(
13 years ago
* 'name' => 'Sam',
* 'age' => 30,
13 years ago
* ));
13 years ago
* ~~~
*
13 years ago
* @param string $table the table that new rows will be inserted into.
* @param array $columns the column data (name=>value) to be inserted into the table.
* @return integer number of rows affected by the execution.
*/
13 years ago
public function insert($table, $columns)
13 years ago
{
$names = array();
$placeholders = array();
$count = 0;
13 years ago
$params = array();
13 years ago
foreach ($columns as $name => $value) {
13 years ago
$names[] = $this->quoteColumnName($name);
13 years ago
if ($value instanceof Expression) {
$placeholders[] = $value->expression;
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
13 years ago
} else {
13 years ago
$placeholders[] = ':p' . $count;
$params[':p' . $count] = $value;
$count++;
}
}
13 years ago
if ($this->query instanceof BaseQuery) {
13 years ago
$this->query->addParams($params);
13 years ago
}
13 years ago
13 years ago
return 'INSERT INTO ' . $this->quoteTableName($table)
13 years ago
. ' (' . implode(', ', $names) . ') VALUES ('
. implode(', ', $placeholders) . ')';
}
/**
* Creates and executes an UPDATE SQL statement.
* The method will properly escape the column names and bind the values to be updated.
13 years ago
* For example,
*
* ~~~
* $params = array();
* $sql = $queryBuilder->update('tbl_user', array(
13 years ago
* 'status' => 1,
13 years ago
* ), 'age > 30', $params);
* ~~~
*
13 years ago
* @param string $table the table to be updated.
* @param array $columns the column data (name=>value) to be updated.
13 years ago
* @param mixed $condition the condition that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify condition.
13 years ago
* @param array $params the parameters to be bound to the query.
13 years ago
* @return integer number of rows affected by the execution.
*/
13 years ago
public function update($table, $columns, $condition = '', $params = array())
13 years ago
{
$lines = array();
$count = 0;
foreach ($columns as $name => $value) {
if ($value instanceof Expression) {
13 years ago
$lines[] = $this->quoteColumnName($name, true) . '=' . $value->expression;
13 years ago
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
13 years ago
} else {
13 years ago
$lines[] = $this->quoteColumnName($name, true) . '=:p' . $count;
13 years ago
$params[':p' . $count] = $value;
$count++;
}
}
13 years ago
if ($this->query instanceof BaseQuery) {
13 years ago
$this->query->addParams($params);
13 years ago
}
13 years ago
$sql = 'UPDATE ' . $this->quoteTableName($table) . ' SET ' . implode(', ', $lines);
13 years ago
if (($where = $this->buildCondition($condition)) !== '') {
13 years ago
$sql .= ' WHERE ' . $where;
}
13 years ago
13 years ago
return $sql;
}
/**
* Creates and executes a DELETE SQL statement.
13 years ago
* For example,
*
* ~~~
* $sql = $queryBuilder->delete('tbl_user', 'status = 0');
* ~~~
*
13 years ago
* @param string $table the table where the data will be deleted from.
13 years ago
* @param mixed $condition the condition that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify condition.
13 years ago
* @param array $params the parameters to be bound to the query.
13 years ago
* @return integer number of rows affected by the execution.
*/
13 years ago
public function delete($table, $condition = '', $params = array())
13 years ago
{
13 years ago
$sql = 'DELETE FROM ' . $this->quoteTableName($table);
13 years ago
if (($where = $this->buildCondition($condition)) !== '') {
13 years ago
$sql .= ' WHERE ' . $where;
}
13 years ago
if ($params !== array() && $this->query instanceof BaseQuery) {
$this->query->addParams($params);
}
13 years ago
return $sql;
13 years ago
}
13 years ago
/**
* Builds a SQL statement for creating a new DB table.
*
* The columns in the new table should be specified as name-definition pairs (e.g. 'name'=>'string'),
* where name stands for a column name which will be properly quoted by the method, and definition
* stands for the column type which can contain an abstract DB type.
13 years ago
* The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
13 years ago
*
* If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
* inserted into the generated SQL.
*
13 years ago
* For example,
*
* ~~~
* $sql = $queryBuilder->createTable('tbl_user', array(
13 years ago
* 'id' => 'pk',
* 'name' => 'string',
* 'age' => 'integer',
13 years ago
* ));
* ~~~
*
13 years ago
* @param string $table the name of the table to be created. The name will be properly quoted by the method.
* @param array $columns the columns (name=>definition) in the new table.
* @param string $options additional SQL fragment that will be appended to the generated SQL.
* @return string the SQL statement for creating a new DB table.
*/
public function createTable($table, $columns, $options = null)
{
$cols = array();
13 years ago
foreach ($columns as $name => $type) {
if (is_string($name)) {
13 years ago
$cols[] = "\t" . $this->quoteColumnName($name) . ' ' . $this->getColumnType($type);
} else {
13 years ago
$cols[] = "\t" . $type;
13 years ago
}
13 years ago
}
13 years ago
$sql = "CREATE TABLE " . $this->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
13 years ago
return $options === null ? $sql : $sql . ' ' . $options;
}
/**
* Builds a SQL statement for renaming a DB table.
13 years ago
* @param string $oldName the table to be renamed. The name will be properly quoted by the method.
13 years ago
* @param string $newName the new table name. The name will be properly quoted by the method.
* @return string the SQL statement for renaming a DB table.
*/
13 years ago
public function renameTable($oldName, $newName)
13 years ago
{
13 years ago
return 'RENAME TABLE ' . $this->quoteTableName($oldName) . ' TO ' . $this->quoteTableName($newName);
13 years ago
}
/**
* Builds a SQL statement for dropping a DB table.
* @param string $table the table to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping a DB table.
*/
public function dropTable($table)
{
13 years ago
return "DROP TABLE " . $this->quoteTableName($table);
13 years ago
}
/**
* Builds a SQL statement for truncating a DB table.
* @param string $table the table to be truncated. The name will be properly quoted by the method.
* @return string the SQL statement for truncating a DB table.
*/
public function truncateTable($table)
13 years ago
{
13 years ago
return "TRUNCATE TABLE " . $this->quoteTableName($table);
13 years ago
}
/**
* Builds a SQL statement for adding a new DB column.
* @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
* @param string $column the name of the new column. The name will be properly quoted by the method.
13 years ago
* @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
13 years ago
* into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
* For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
* @return string the SQL statement for adding a new column.
*/
public function addColumn($table, $column, $type)
{
13 years ago
return 'ALTER TABLE ' . $this->quoteTableName($table)
. ' ADD ' . $this->quoteColumnName($column) . ' '
13 years ago
. $this->getColumnType($type);
}
13 years ago
13 years ago
/**
* Builds a SQL statement for dropping a DB column.
* @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
* @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping a DB column.
*/
public function dropColumn($table, $column)
{
13 years ago
return "ALTER TABLE " . $this->quoteTableName($table)
. " DROP COLUMN " . $this->quoteColumnName($column, true);
13 years ago
}
/**
* Builds a SQL statement for renaming a column.
* @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
13 years ago
* @param string $oldName the old name of the column. The name will be properly quoted by the method.
13 years ago
* @param string $newName the new name of the column. The name will be properly quoted by the method.
* @return string the SQL statement for renaming a DB column.
*/
13 years ago
public function renameColumn($table, $oldName, $newName)
13 years ago
{
13 years ago
return "ALTER TABLE " . $this->quoteTableName($table)
. " RENAME COLUMN " . $this->quoteColumnName($oldName, true)
. " TO " . $this->quoteColumnName($newName, true);
13 years ago
}
/**
* Builds a SQL statement for changing the definition of a column.
* @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
* @param string $column the name of the column to be changed. The name will be properly quoted by the method.
13 years ago
* @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
* column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
* in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
* will become 'varchar(255) not null'.
13 years ago
* @return string the SQL statement for changing the definition of a column.
*/
public function alterColumn($table, $column, $type)
{
13 years ago
return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
. $this->quoteColumnName($column, true) . ' '
. $this->quoteColumnName($column, true) . ' '
13 years ago
. $this->getColumnType($type);
}
/**
* Builds a SQL statement for adding a foreign key constraint to an existing table.
* The method will properly quote the table and column names.
* @param string $name the name of the foreign key constraint.
* @param string $table the table that the foreign key constraint will be added to.
13 years ago
* @param string|array $columns the name of the column to that the constraint will be added on.
* If there are multiple columns, separate them with commas or use an array to represent them.
13 years ago
* @param string $refTable the table that the foreign key references to.
13 years ago
* @param string|array $refColumns the name of the column that the foreign key references to.
* If there are multiple columns, separate them with commas or use an array to represent them.
13 years ago
* @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
* @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
* @return string the SQL statement for adding a foreign key constraint to an existing table.
*/
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
13 years ago
$sql = 'ALTER TABLE ' . $this->quoteTableName($table)
. ' ADD CONSTRAINT ' . $this->quoteColumnName($name)
. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
. ' REFERENCES ' . $this->quoteTableName($refTable)
. ' (' . $this->buildColumns($refColumns) . ')';
13 years ago
if ($delete !== null) {
13 years ago
$sql .= ' ON DELETE ' . $delete;
13 years ago
}
if ($update !== null) {
13 years ago
$sql .= ' ON UPDATE ' . $update;
13 years ago
}
13 years ago
return $sql;
}
/**
* Builds a SQL statement for dropping a foreign key constraint.
* @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
* @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping a foreign key constraint.
*/
public function dropForeignKey($name, $table)
{
13 years ago
return 'ALTER TABLE ' . $this->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->quoteColumnName($name);
13 years ago
}
/**
* Builds a SQL statement for creating a new index.
* @param string $name the name of the index. The name will be properly quoted by the method.
* @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
13 years ago
* @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
* separate them with commas or use an array to represent them. Each column name will be properly quoted
* by the method, unless a parenthesis is found in the name.
13 years ago
* @param boolean $unique whether to add UNIQUE constraint on the created index.
* @return string the SQL statement for creating a new index.
*/
13 years ago
public function createIndex($name, $table, $columns, $unique = false)
13 years ago
{
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
13 years ago
. $this->quoteTableName($name) . ' ON '
. $this->quoteTableName($table)
. ' (' . $this->buildColumns($columns) . ')';
13 years ago
}
/**
* Builds a SQL statement for dropping an index.
* @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
* @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping an index.
*/
public function dropIndex($name, $table)
{
13 years ago
return 'DROP INDEX ' . $this->quoteTableName($name) . ' ON ' . $this->quoteTableName($table);
13 years ago
}
13 years ago
/**
* Resets the sequence value of a table's primary key.
* The sequence will be reset such that the primary key of the next new row inserted
* will have the specified value or 1.
13 years ago
* @param string $table the table schema whose primary key sequence will be reset
13 years ago
* @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
* the next new row's primary key will have a value 1.
*/
public function resetSequence($table, $value = null)
{
}
/**
* Enables or disables integrity check.
* @param boolean $check whether to turn on or off the integrity check.
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
*/
public function checkIntegrity($check = true, $schema = '')
{
}
/**
* Converts an abstract column type into a physical column type.
13 years ago
* The conversion is done using the type map specified in [[typeMap]].
13 years ago
* The following abstract column types are supported (using MySQL as an example to explain the corresponding
13 years ago
* physical types):
13 years ago
*
13 years ago
* - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
* - `string`: string type, will be converted into "varchar(255)"
* - `text`: a long string type, will be converted into "text"
* - `smallint`: a small integer type, will be converted into "smallint(6)"
* - `integer`: integer type, will be converted into "int(11)"
* - `bigint`: a big integer type, will be converted into "bigint(20)"
* - `boolean`: boolean type, will be converted into "tinyint(1)"
* - `float``: float number type, will be converted into "float"
* - `decimal`: decimal number type, will be converted into "decimal"
* - `datetime`: datetime type, will be converted into "datetime"
* - `timestamp`: timestamp type, will be converted into "timestamp"
* - `time`: time type, will be converted into "time"
* - `date`: date type, will be converted into "date"
* - `money`: money type, will be converted into "decimal(19,4)"
* - `binary`: binary data type, will be converted into "blob"
13 years ago
*
* If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
13 years ago
* the first part will be converted, and the rest of the parts will be appended to the converted result.
13 years ago
* For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
13 years ago
*
* If a type cannot be found in [[typeMap]], it will be returned without any change.
13 years ago
* @param string $type abstract column type
* @return string physical column type.
*/
13 years ago
public function getColumnType($type)
{
13 years ago
if (isset($this->typeMap[$type])) {
return $this->typeMap[$type];
13 years ago
} elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
if (isset($this->typeMap[$matches[0]])) {
return preg_replace('/^\w+/', $this->typeMap[$matches[0]], $type);
}
}
return $type;
}
/**
13 years ago
* Parses the condition specification and generates the corresponding SQL expression.
13 years ago
* @param string|array $condition the condition specification. Please refer to [[BaseQuery::where()]]
13 years ago
* on how to specify a condition.
* @return string the generated SQL expression
* @throws \yii\db\Exception if the condition is in bad format
13 years ago
*/
public function buildCondition($condition)
{
13 years ago
static $builders = array(
'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',
);
13 years ago
if (!is_array($condition)) {
13 years ago
return (string)$condition;
13 years ago
} elseif ($condition === array()) {
return '';
}
13 years ago
if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
$operator = $condition[0];
if (isset($builders[$operator])) {
$method = $builders[$operator];
array_shift($condition);
return $this->$method($operator, $condition);
} else {
throw new Exception('Found unknown operator in query: ' . $operator);
}
} else { // hash format: 'column1'=>'value1', 'column2'=>'value2', ...
return $this->buildHashCondition($condition);
}
}
13 years ago
13 years ago
private function buildHashCondition($condition)
{
$parts = array();
foreach ($condition as $column => $value) {
if (is_array($value)) { // IN condition
$parts[] = $this->buildInCondition('in', array($column, $value));
} else {
if (strpos($column, '(') === false) {
$column = $this->quoteColumnName($column);
}
if ($value === null) {
$parts[] = "$column IS NULL";
} elseif (is_string($value)) {
$parts[] = "$column=" . $this->connection->quoteValue($value);
} else {
$parts[] = "$column=$value";
13 years ago
}
}
}
13 years ago
return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
13 years ago
}
13 years ago
13 years ago
private function buildAndCondition($operator, $operands)
{
$parts = array();
foreach ($operands as $operand) {
if (is_array($operand)) {
$operand = $this->buildCondition($operand);
}
if ($operand !== '') {
$parts[] = $operand;
}
13 years ago
}
13 years ago
if ($parts !== array()) {
$operator = strtoupper($operator);
13 years ago
return '(' . implode(") $operator (", $parts) . ')';
} else {
return '';
}
}
private function buildBetweenCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1], $operands[2])) {
throw new Exception("Operator '$operator' requires three operands.");
}
list($column, $value1, $value2) = $operands;
13 years ago
if (strpos($column, '(') === false) {
13 years ago
$column = $this->quoteColumnName($column);
13 years ago
}
13 years ago
$value1 = is_string($value1) ? $this->connection->quoteValue($value1) : (string)$value1;
$value2 = is_string($value2) ? $this->connection->quoteValue($value2) : (string)$value2;
13 years ago
13 years ago
return "$column $operator $value1 AND $value2";
}
private function buildInCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new Exception("Operator '$operator' requires two operands.");
13 years ago
}
13 years ago
list($column, $values) = $operands;
13 years ago
if (!is_array($values)) {
$values = array($values);
}
13 years ago
if ($values === array()) {
return $operator === 'in' ? '0=1' : '';
13 years ago
}
13 years ago
foreach ($values as $i => $value) {
$values[$i] = is_string($value) ? $this->connection->quoteValue($value) : (string)$value;
}
13 years ago
13 years ago
if (strpos($column, '(') === false) {
$column = $this->quoteColumnName($column);
}
$operator = strtoupper($operator);
13 years ago
return "$column $operator (" . implode(', ', $values) . ')';
}
private function buildLikeCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new Exception("Operator '$operator' requires two operands.");
}
list($column, $values) = $operands;
if (!is_array($values)) {
$values = array($values);
}
if ($values === array()) {
return $operator === 'like' || $operator === 'or like' ? '0=1' : '';
}
if ($operator === 'like' || $operator === 'not like') {
$andor = ' AND ';
13 years ago
} else {
$andor = ' OR ';
13 years ago
$operator = $operator === 'or like' ? 'like' : 'not like';
}
if (strpos($column, '(') === false) {
$column = $this->quoteColumnName($column);
}
$operator = strtoupper($operator);
13 years ago
$parts = array();
foreach ($values as $value) {
$parts[] = "$column $operator " . $this->connection->quoteValue($value);
13 years ago
}
13 years ago
13 years ago
return implode($andor, $parts);
13 years ago
}
13 years ago
/**
13 years ago
* @param string|array $columns
* @param boolean $distinct
* @param string $selectOption
13 years ago
* @return string the SELECT clause built from [[query]].
*/
13 years ago
public function buildSelect($columns, $distinct = false, $selectOption = null)
13 years ago
{
13 years ago
$select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
if ($selectOption !== null) {
$select .= ' ' . $selectOption;
13 years ago
}
13 years ago
13 years ago
if (empty($columns)) {
return $select . ' *';
}
13 years ago
if ($this->autoQuote) {
13 years ago
$driver = $this->connection->driver;
13 years ago
if (!is_array($columns)) {
if (strpos($columns, '(') !== false) {
return $select . ' ' . $columns;
13 years ago
} else {
13 years ago
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
}
}
foreach ($columns as $i => $column) {
if (is_object($column)) {
$columns[$i] = (string)$column;
} elseif (strpos($column, '(') === false) {
13 years ago
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
13 years ago
$columns[$i] = $driver->quoteColumnName($matches[1]) . ' AS ' . $driver->quoteSimpleColumnName($matches[2]);
13 years ago
} else {
13 years ago
$columns[$i] = $driver->quoteColumnName($column);
13 years ago
}
13 years ago
}
}
}
13 years ago
if (is_array($columns)) {
$columns = implode(', ', $columns);
}
return $select . ' ' . $columns;
13 years ago
}
13 years ago
/**
13 years ago
* @param string|array $tables
13 years ago
* @return string the FROM clause built from [[query]].
*/
13 years ago
public function buildFrom($tables)
13 years ago
{
13 years ago
if (empty($tables)) {
13 years ago
return '';
}
13 years ago
if ($this->autoQuote) {
13 years ago
$driver = $this->connection->driver;
13 years ago
if (!is_array($tables)) {
if (strpos($tables, '(') !== false) {
return 'FROM ' . $tables;
13 years ago
} else {
13 years ago
$tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
13 years ago
}
}
13 years ago
foreach ($tables as $i => $table) {
if (strpos($table, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias
13 years ago
$tables[$i] = $driver->quoteTableName($matches[1]) . ' ' . $driver->quoteTableName($matches[2]);
13 years ago
} else {
13 years ago
$tables[$i] = $driver->quoteTableName($table);
13 years ago
}
}
}
}
if (is_array($tables)) {
$tables = implode(', ', $tables);
13 years ago
}
13 years ago
return 'FROM ' . $tables;
13 years ago
}
13 years ago
13 years ago
/**
13 years ago
* @param string|array $joins
13 years ago
* @return string the JOIN clause built from [[query]].
*/
13 years ago
public function buildJoin($joins)
13 years ago
{
if (empty($joins)) {
return '';
}
if (is_string($joins)) {
return $joins;
}
13 years ago
13 years ago
foreach ($joins as $i => $join) {
13 years ago
if (is_array($join)) { // 0:join type, 1:table name, 2:on-condition
13 years ago
if (isset($join[0], $join[1])) {
$table = $join[1];
13 years ago
if ($this->autoQuote && strpos($table, '(') === false) {
13 years ago
$driver = $this->connection->driver;
13 years ago
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias
13 years ago
$table = $driver->quoteTableName($matches[1]) . ' ' . $driver->quoteTableName($matches[2]);
13 years ago
} else {
13 years ago
$table = $driver->quoteTableName($table);
13 years ago
}
}
$joins[$i] = strtoupper($join[0]) . ' ' . $table;
13 years ago
if (isset($join[2])) {
$condition = $this->buildCondition($join[2]);
if ($condition !== '') {
$joins[$i] .= ' ON ' . $this->buildCondition($join[2]);
}
13 years ago
}
13 years ago
} else {
13 years ago
throw new Exception('A join clause must be specified as an array of at least two elements.');
13 years ago
}
}
}
13 years ago
13 years ago
return implode($this->separator, $joins);
13 years ago
}
13 years ago
/**
13 years ago
* @param string|array $condition
13 years ago
* @return string the WHERE clause built from [[query]].
*/
13 years ago
public function buildWhere($condition)
13 years ago
{
13 years ago
$where = $this->buildCondition($condition);
return $where === '' ? '' : 'WHERE ' . $where;
13 years ago
}
13 years ago
/**
13 years ago
* @param string|array $columns
* @return string the GROUP BY clause
13 years ago
*/
public function buildGroup($columns)
13 years ago
{
13 years ago
if (empty($columns)) {
13 years ago
return '';
13 years ago
} else {
13 years ago
return 'GROUP BY ' . $this->buildColumns($columns);
13 years ago
}
13 years ago
}
13 years ago
/**
13 years ago
* @param string|array $condition
13 years ago
* @return string the HAVING clause built from [[query]].
*/
13 years ago
public function buildHaving($condition)
13 years ago
{
13 years ago
$having = $this->buildCondition($condition);
return $having === '' ? '' : 'HAVING ' . $having;
13 years ago
}
13 years ago
/**
13 years ago
* @param string|array $columns
13 years ago
* @return string the ORDER BY clause built from [[query]].
*/
public function buildOrder($columns)
13 years ago
{
13 years ago
if (empty($columns)) {
13 years ago
return '';
}
13 years ago
if ($this->autoQuote) {
13 years ago
$driver = $this->connection->driver;
13 years ago
if (!is_array($columns)) {
if (strpos($columns, '(') !== false) {
return 'ORDER BY ' . $columns;
13 years ago
} else {
13 years ago
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
13 years ago
}
}
13 years ago
foreach ($columns as $i => $column) {
if (is_object($column)) {
$columns[$i] = (string)$column;
} elseif (strpos($column, '(') === false) {
if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
13 years ago
$columns[$i] = $driver->quoteColumnName($matches[1]) . ' ' . $matches[2];
13 years ago
} else {
13 years ago
$columns[$i] = $driver->quoteColumnName($column);
13 years ago
}
}
}
}
if (is_array($columns)) {
$columns = implode(', ', $columns);
13 years ago
}
13 years ago
return 'ORDER BY ' . $columns;
13 years ago
}
13 years ago
/**
13 years ago
* @param integer $limit
* @param integer $offset
13 years ago
* @return string the LIMIT and OFFSET clauses built from [[query]].
*/
13 years ago
public function buildLimit($limit, $offset)
13 years ago
{
13 years ago
$sql = '';
13 years ago
if ($limit !== null && $limit >= 0) {
$sql = 'LIMIT ' . (int)$limit;
13 years ago
}
13 years ago
if ($offset > 0) {
$sql .= ' OFFSET ' . (int)$offset;
13 years ago
}
return ltrim($sql);
13 years ago
}
13 years ago
/**
13 years ago
* @param string|array $unions
13 years ago
* @return string the UNION clause built from [[query]].
*/
13 years ago
public function buildUnion($unions)
13 years ago
{
13 years ago
if (empty($unions)) {
return '';
}
if (!is_array($unions)) {
$unions = array($unions);
}
foreach ($unions as $i => $union) {
13 years ago
if ($union instanceof BaseQuery) {
$unions[$i] = $this->build($union);
13 years ago
}
}
return "UNION (\n" . implode("\n) UNION (\n", $unions) . "\n)";
13 years ago
}
13 years ago
/**
* Processes columns and properly quote them if necessary.
* This method will quote columns if [[autoQuote]] is true.
* 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
*/
protected function buildColumns($columns)
{
if ($this->autoQuote) {
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) {
13 years ago
$columns[$i] = $this->quoteColumnName($column);
13 years ago
}
}
}
return is_array($columns) ? implode(', ', $columns) : $columns;
}
/**
* Quotes a table name for use in a query.
* This method will perform name quoting only when [[autoQuote]] is true.
* @param string $name table name
* @param boolean $simple whether the name should be treated as a simple table name without any prefix.
* @return string the properly quoted table name
*/
protected function quoteTableName($name, $simple = false)
{
if ($this->autoQuote) {
13 years ago
return $this->connection->quoteTableName($name, $simple);
13 years ago
} else {
return $name;
}
}
/**
* Quotes a column name for use in a query.
* This method will perform name quoting only when [[autoQuote]] is true.
* @param string $name column name
* @param boolean $simple whether the name should be treated as a simple column name without any prefix.
* @return string the properly quoted column name
*/
protected function quoteColumnName($name, $simple = false)
{
if ($this->autoQuote) {
13 years ago
return $this->connection->quoteColumnName($name, $simple);
13 years ago
} else {
return $name;
}
}
13 years ago
}