diff --git a/framework/db/dao/ColumnSchema.php b/framework/db/dao/ColumnSchema.php
index 6fb34dcf4c..0ab2819bcf 100644
--- a/framework/db/dao/ColumnSchema.php
+++ b/framework/db/dao/ColumnSchema.php
@@ -19,7 +19,7 @@ namespace yii\db\dao;
class ColumnSchema extends \yii\base\Component
{
/**
- * The followings are supported abstract column data types.
+ * The followings are the supported abstract column data types.
*/
const TYPE_STRING = 'string';
const TYPE_TEXT = 'text';
diff --git a/framework/db/dao/QueryBuilder.php b/framework/db/dao/QueryBuilder.php
index cf2598c171..abdd2ce335 100644
--- a/framework/db/dao/QueryBuilder.php
+++ b/framework/db/dao/QueryBuilder.php
@@ -34,7 +34,7 @@ class QueryBuilder extends \yii\base\Object
*/
public $connection;
/**
- * @var Driver the database driver
+ * @var Driver the database driver used for this query builder.
*/
public $driver;
/**
@@ -43,9 +43,10 @@ class QueryBuilder extends \yii\base\Object
*/
public $separator = " ";
/**
- * @var Query the Query object. This is set when calling [[build()]] to generate a non-SELECT SQL statement.
+ * @var Query the Query object that is currently processed by the query builder to generate a SQL statement.
+ * After the SQL statement is generated by [[build()]], this property will be set null.
*/
- private $_query;
+ public $query;
/**
* Constructor.
@@ -66,33 +67,43 @@ class QueryBuilder extends \yii\base\Object
*/
public function build($query)
{
+ $this->query = $query;
if ($query->operation !== null) {
// non-SELECT query
- $this->_query = $query;
$method = array_shift($query->operation);
$sql = call_user_func_array(array($this, $method), $query->operation);
- $this->_query = null;
- return $sql;
} else {
// SELECT query
$clauses = array(
- $this->buildSelect($query),
- $this->buildFrom($query),
- $this->buildJoin($query),
- $this->buildWhere($query),
- $this->buildGroupBy($query),
- $this->buildHaving($query),
- $this->buildUnion($query),
- $this->buildOrderBy($query),
- $this->buildLimit($query),
+ $this->buildSelect(),
+ $this->buildFrom(),
+ $this->buildJoin(),
+ $this->buildWhere(),
+ $this->buildGroupBy(),
+ $this->buildHaving(),
+ $this->buildUnion(),
+ $this->buildOrderBy(),
+ $this->buildLimit(),
);
- return implode($this->separator, array_filter($clauses));
+ $sql = implode($this->separator, array_filter($clauses));
}
+ $this->query = null;
+ return $sql;
}
/**
* Creates and executes an INSERT SQL statement.
* The method will properly escape the column names, and bind the values to be inserted.
+ * For example,
+ *
+ * ~~~
+ * $params = array();
+ * $sql = $queryBuilder->insert('tbl_user', array(
+ * 'name' => 'Sam',
+ * 'age' => 30,
+ * ), $params);
+ * ~~~
+ *
* @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.
* @param array $params the parameters to be bound to the query. This method will modify
@@ -117,8 +128,8 @@ class QueryBuilder extends \yii\base\Object
$count++;
}
}
- if ($this->_query instanceof Query) {
- $this->_query->addParams($params);
+ if ($this->query instanceof Query) {
+ $this->query->addParams($params);
}
return 'INSERT INTO ' . $this->driver->quoteTableName($table)
@@ -129,6 +140,15 @@ class QueryBuilder extends \yii\base\Object
/**
* Creates and executes an UPDATE SQL statement.
* The method will properly escape the column names and bind the values to be updated.
+ * For example,
+ *
+ * ~~~
+ * $params = array();
+ * $sql = $queryBuilder->update('tbl_user', array(
+ * 'status' => 1,
+ * ), 'age > 30', $params);
+ * ~~~
+ *
* @param string $table the table to be updated.
* @param array $columns the column data (name=>value) to be updated.
* @param mixed $condition the condition that will be put in the WHERE part. Please
@@ -153,8 +173,8 @@ class QueryBuilder extends \yii\base\Object
$count++;
}
}
- if ($this->_query instanceof Query) {
- $this->_query->addParams($params);
+ if ($this->query instanceof Query) {
+ $this->query->addParams($params);
}
$sql = 'UPDATE ' . $this->driver->quoteTableName($table) . ' SET ' . implode(', ', $lines);
if (($where = $this->buildCondition($condition)) != '') {
@@ -166,6 +186,12 @@ class QueryBuilder extends \yii\base\Object
/**
* Creates and executes a DELETE SQL statement.
+ * For example,
+ *
+ * ~~~
+ * $sql = $queryBuilder->delete('tbl_user', 'status = 0');
+ * ~~~
+ *
* @param string $table the table where the data will be deleted from.
* @param mixed $condition the condition that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify condition.
@@ -191,6 +217,16 @@ class QueryBuilder extends \yii\base\Object
* If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
* inserted into the generated SQL.
*
+ * For example,
+ *
+ * ~~~
+ * $sql = $queryBuilder->createTable('tbl_user', array(
+ * 'id' => 'pk',
+ * 'name' => 'string',
+ * 'age' => 'integer',
+ * ));
+ * ~~~
+ *
* @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.
@@ -201,7 +237,7 @@ class QueryBuilder extends \yii\base\Object
$cols = array();
foreach ($columns as $name => $type) {
if (is_string($name)) {
- $cols[] = "\t" . $this->driver->quoteColumnName($name) . ' ' . $this->driver->getColumnType($type);
+ $cols[] = "\t" . $this->driver->quoteColumnName($name) . ' ' . $this->getColumnType($type);
} else
{
$cols[] = "\t" . $type;
@@ -213,13 +249,13 @@ class QueryBuilder extends \yii\base\Object
/**
* Builds a SQL statement for renaming a DB table.
- * @param string $table the table to be renamed. The name will be properly quoted by the method.
+ * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
* @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.
*/
- public function renameTable($table, $newName)
+ public function renameTable($oldName, $newName)
{
- return 'RENAME TABLE ' . $this->driver->quoteTableName($table) . ' TO ' . $this->driver->quoteTableName($newName);
+ return 'RENAME TABLE ' . $this->driver->quoteTableName($oldName) . ' TO ' . $this->driver->quoteTableName($newName);
}
/**
@@ -288,9 +324,10 @@ class QueryBuilder extends \yii\base\Object
* 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.
- * @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'.
+ * @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'.
* @return string the SQL statement for changing the definition of a column.
*/
public function alterColumn($table, $column, $type)
@@ -306,20 +343,26 @@ class QueryBuilder extends \yii\base\Object
* 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.
- * @param string $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas.
+ * @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.
* @param string $refTable the table that the foreign key references to.
- * @param string $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
+ * @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.
* @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)
{
- $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
+ if (!is_array($columns)) {
+ $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
+ }
foreach ($columns as $i => $col) {
$columns[$i] = $this->driver->quoteColumnName($col);
}
- $refColumns = preg_split('/\s*,\s*/', $refColumns, -1, PREG_SPLIT_NO_EMPTY);
+ if (!is_array($refColumns)) {
+ $refColumns = preg_split('/\s*,\s*/', $refColumns, -1, PREG_SPLIT_NO_EMPTY);
+ }
foreach ($refColumns as $i => $col) {
$refColumns[$i] = $this->driver->quoteColumnName($col);
}
@@ -353,27 +396,27 @@ class QueryBuilder extends \yii\base\Object
* 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.
- * @param string $column the column(s) that should be included in the index. If there are multiple columns, please separate them
- * by commas. Each column name will be properly quoted by the method, unless a parenthesis is found in the name.
+ * @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.
* @param boolean $unique whether to add UNIQUE constraint on the created index.
* @return string the SQL statement for creating a new index.
*/
- public function createIndex($name, $table, $column, $unique = false)
+ public function createIndex($name, $table, $columns, $unique = false)
{
- $cols = array();
- $columns = preg_split('/\s*,\s*/', $column, -1, PREG_SPLIT_NO_EMPTY);
- foreach ($columns as $col)
- {
- if (strpos($col, '(') !== false) {
- $cols[] = $col;
- } else
- {
- $cols[] = $this->driver->quoteColumnName($col);
+ if (!is_array($columns)) {
+ $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
+ }
+ foreach ($columns as $i => $column) {
+ if (strpos($column, '(') !== false) {
+ $columns[$i] = $column;
+ } else {
+ $columns[$i] = $this->driver->quoteColumnName($column);
}
}
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
. $this->driver->quoteTableName($name) . ' ON '
- . $this->driver->quoteTableName($table) . ' (' . implode(', ', $cols) . ')';
+ . $this->driver->quoteTableName($table) . ' (' . implode(', ', $columns) . ')';
}
/**
@@ -391,7 +434,7 @@ class QueryBuilder extends \yii\base\Object
* 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.
- * @param CDbTableSchema $table the table schema whose primary key sequence will be reset
+ * @param string $table the table schema whose primary key sequence will be reset
* @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.
*/
@@ -411,26 +454,30 @@ class QueryBuilder extends \yii\base\Object
/**
* Converts an abstract column type into a physical column type.
* The conversion is done using the type map specified in [[typeMap]].
- * These abstract column types are supported (using MySQL as example to explain the corresponding
+ * The following abstract column types are supported (using MySQL as an example to explain the corresponding
* physical types):
- *
- * - 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"
- * - integer: integer type, will be converted into "int(11)"
- * - 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"
- * - binary: binary data type, will be converted into "blob"
- *
+ *
+ * - `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"
*
* If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
- * the first part will be converted, and the rest of the parts will be appended to the conversion result.
+ * the first part will be converted, and the rest of the parts will be appended to the converted result.
* For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
+ *
+ * If a type cannot be found in [[typeMap]], it will be returned without any change.
* @param string $type abstract column type
* @return string physical column type.
*/
@@ -438,201 +485,20 @@ class QueryBuilder extends \yii\base\Object
{
if (isset($this->typeMap[$type])) {
return $this->typeMap[$type];
- } elseif (($pos = strpos($type, ' ')) !== false) {
- $t = substr($type, 0, $pos);
- return (isset($this->typeMap[$t]) ? $this->typeMap[$t] : $t) . substr($type, $pos);
- } else {
- return $type;
- }
- }
-
- protected function buildSelect($query)
- {
- $select = $query->distinct ? 'SELECT DISTINCT' : 'SELECT';
- if ($query->selectOption != '') {
- $select .= ' ' . $query->selectOption;
- }
-
- $columns = $query->select;
- if (empty($columns)) {
- return $select . ' *';
- }
-
- if (is_string($columns)) {
- if (strpos($columns, '(') !== false) {
- return $select . ' ' . $columns;
- }
- $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) {
- if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-\.])$/', $column, $matches)) {
- $columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' AS ' . $this->driver->quoteSimpleColumnName($matches[2]);
- } else {
- $columns[$i] = $this->connection->quoteColumnName($column);
- }
+ } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
+ if (isset($this->typeMap[$matches[0]])) {
+ return preg_replace('/^\w+/', $this->typeMap[$matches[0]], $type);
}
}
-
- return $select . ' ' . implode(', ', $columns);
+ return $type;
}
- protected function buildFrom($query)
- {
- if (empty($query->from)) {
- return '';
- }
-
- $tables = $query->from;
- if (is_string($tables) && strpos($tables, '(') !== false) {
- return 'FROM ' . $tables;
- }
-
- if (!is_array($tables)) {
- $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
- }
- foreach ($tables as $i => $table) {
- if (strpos($table, '(') === false) {
- if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias
- $tables[$i] = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]);
- } else {
- $tables[$i] = $this->connection->quoteTableName($table);
- }
- }
- }
-
- return 'FROM ' . implode(', ', $tables);
- }
-
- protected function buildJoin($query)
- {
- $joins = $query->join;
- if (empty($joins)) {
- return '';
- }
- if (is_string($joins)) {
- return $joins;
- }
-
- foreach ($joins as $i => $join) {
- if (is_array($join)) { // join type, table name, on-condition
- if (isset($join[0], $join[1])) {
- $table = $join[1];
- if (strpos($table, '(') === false) {
- if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias
- $table = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]);
- } else {
- $table = $this->connection->quoteTableName($table);
- }
- }
- $joins[$i] = strtoupper($join[0]) . ' ' . $table;
- if (isset($join[2])) { // join condition
- $joins[$i] .= ' ON ' . $this->buildCondition($join[2]);
- }
- } else {
- throw new Exception('The join clause may be specified as an array of at least two elements.');
- }
- }
- }
-
- return implode("\n", $joins);
- }
-
- protected function buildWhere($query)
- {
- $where = $this->buildCondition($query->where);
- return empty($where) ? '' : 'WHERE ' . $where;
- }
-
- protected function buildGroupBy($query)
- {
- $columns = $query->groupBy;
- if (empty($columns)) {
- return '';
- }
- if (is_string($columns) && strpos($columns, '(') !== false) {
- return 'GROUP BY ' . $columns;
- }
-
- if (!is_array($columns)) {
- $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) {
- $columns[$i] = $this->connection->quoteColumnName($column);
- }
- }
- return 'GROUP BY ' . implode(', ', $columns);
- }
-
- protected function buildHaving($query)
- {
- $having = $this->buildCondition($query->having);
- return empty($having) ? '' : 'HAVING ' . $having;
- }
-
- protected function buildOrderBy($query)
- {
- $columns = $query->orderBy;
- if (empty($columns)) {
- return '';
- }
- if (is_string($columns) && strpos($columns, '(') !== false) {
- return 'ORDER BY ' . $columns;
- }
-
- if (!is_array($columns)) {
- $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) {
- if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
- $columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' ' . strtoupper($matches[2]);
- } else {
- $columns[$i] = $this->connection->quoteColumnName($column);
- }
- }
- }
- return 'ORDER BY ' . implode(', ', $columns);
- }
-
- protected function buildLimit($query)
- {
- $sql = '';
- if ($query->limit !== null && $query->limit >= 0) {
- $sql = 'LIMIT ' . (int)$query->limit;
- }
- if ($query->offset > 0) {
- $sql .= ' OFFSET ' . (int)$query->offset;
- }
- return ltrim($sql);
- }
-
- protected function buildUnion($query)
- {
- $unions = $query->union;
- if (empty($unions)) {
- return '';
- }
- if (!is_array($unions)) {
- $unions = array($unions);
- }
- foreach ($unions as $i => $union) {
- if ($union instanceof Query) {
- $unions[$i] = $union->getSql($this->connection);
- }
- }
- return "UNION (\n" . implode("\n) UNION (\n", $unions) . "\n)";
- }
-
- protected function buildCondition($condition)
+ /**
+ * Generates a SQL condition from the given PHP representation.
+ * @param string|array $condition the PHP representation of the SQL condition
+ * @return string the generated SQL condition.
+ */
+ public function buildCondition($condition)
{
if (!is_array($condition)) {
return $condition;
@@ -710,4 +576,217 @@ class QueryBuilder extends \yii\base\Object
throw new Exception('Unknown operator: ' . $operator);
}
+
+ /**
+ * @return string the SELECT clause built from [[query]].
+ */
+ protected function buildSelect()
+ {
+ $select = $this->query->distinct ? 'SELECT DISTINCT' : 'SELECT';
+ if ($this->query->selectOption != '') {
+ $select .= ' ' . $this->query->selectOption;
+ }
+
+ $columns = $this->query->select;
+ if (empty($columns)) {
+ return $select . ' *';
+ }
+
+ if (is_string($columns)) {
+ if (strpos($columns, '(') !== false) {
+ return $select . ' ' . $columns;
+ }
+ $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) {
+ if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-\.])$/', $column, $matches)) {
+ $columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' AS ' . $this->driver->quoteSimpleColumnName($matches[2]);
+ } else {
+ $columns[$i] = $this->connection->quoteColumnName($column);
+ }
+ }
+ }
+
+ return $select . ' ' . implode(', ', $columns);
+ }
+
+ /**
+ * @return string the FROM clause built from [[query]].
+ */
+ protected function buildFrom()
+ {
+ if (empty($this->query->from)) {
+ return '';
+ }
+
+ $tables = $this->query->from;
+ if (is_string($tables) && strpos($tables, '(') !== false) {
+ return 'FROM ' . $tables;
+ }
+
+ if (!is_array($tables)) {
+ $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
+ }
+ foreach ($tables as $i => $table) {
+ if (strpos($table, '(') === false) {
+ if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias
+ $tables[$i] = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]);
+ } else {
+ $tables[$i] = $this->connection->quoteTableName($table);
+ }
+ }
+ }
+
+ return 'FROM ' . implode(', ', $tables);
+ }
+
+ /**
+ * @return string the JOIN clause built from [[query]].
+ */
+ protected function buildJoin()
+ {
+ $joins = $this->query->join;
+ if (empty($joins)) {
+ return '';
+ }
+ if (is_string($joins)) {
+ return $joins;
+ }
+
+ foreach ($joins as $i => $join) {
+ if (is_array($join)) { // join type, table name, on-condition
+ if (isset($join[0], $join[1])) {
+ $table = $join[1];
+ if (strpos($table, '(') === false) {
+ if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias
+ $table = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]);
+ } else {
+ $table = $this->connection->quoteTableName($table);
+ }
+ }
+ $joins[$i] = strtoupper($join[0]) . ' ' . $table;
+ if (isset($join[2])) { // join condition
+ $joins[$i] .= ' ON ' . $this->buildCondition($join[2]);
+ }
+ } else {
+ throw new Exception('A join clause must be specified as an array of at least two elements.');
+ }
+ }
+ }
+
+ return implode("\n", $joins);
+ }
+
+ /**
+ * @return string the WHERE clause built from [[query]].
+ */
+ protected function buildWhere()
+ {
+ $where = $this->buildCondition($this->query->where);
+ return empty($where) ? '' : 'WHERE ' . $where;
+ }
+
+ /**
+ * @return string the GROUP BY clause built from [[query]].
+ */
+ protected function buildGroupBy()
+ {
+ $columns = $this->query->groupBy;
+ if (empty($columns)) {
+ return '';
+ }
+ if (is_string($columns) && strpos($columns, '(') !== false) {
+ return 'GROUP BY ' . $columns;
+ }
+
+ if (!is_array($columns)) {
+ $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) {
+ $columns[$i] = $this->connection->quoteColumnName($column);
+ }
+ }
+ return 'GROUP BY ' . implode(', ', $columns);
+ }
+
+ /**
+ * @return string the HAVING clause built from [[query]].
+ */
+ protected function buildHaving()
+ {
+ $having = $this->buildCondition($this->query->having);
+ return empty($having) ? '' : 'HAVING ' . $having;
+ }
+
+ /**
+ * @return string the ORDER BY clause built from [[query]].
+ */
+ protected function buildOrderBy()
+ {
+ $columns = $this->query->orderBy;
+ if (empty($columns)) {
+ return '';
+ }
+ if (is_string($columns) && strpos($columns, '(') !== false) {
+ return 'ORDER BY ' . $columns;
+ }
+
+ if (!is_array($columns)) {
+ $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) {
+ if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
+ $columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' ' . strtoupper($matches[2]);
+ } else {
+ $columns[$i] = $this->connection->quoteColumnName($column);
+ }
+ }
+ }
+ return 'ORDER BY ' . implode(', ', $columns);
+ }
+
+ /**
+ * @return string the LIMIT and OFFSET clauses built from [[query]].
+ */
+ protected function buildLimit()
+ {
+ $sql = '';
+ if ($this->query->limit !== null && $this->query->limit >= 0) {
+ $sql = 'LIMIT ' . (int)$this->query->limit;
+ }
+ if ($this->query->offset > 0) {
+ $sql .= ' OFFSET ' . (int)$this->query->offset;
+ }
+ return ltrim($sql);
+ }
+
+ /**
+ * @return string the UNION clause built from [[query]].
+ */
+ protected function buildUnion()
+ {
+ $unions = $this->query->union;
+ if (empty($unions)) {
+ return '';
+ }
+ if (!is_array($unions)) {
+ $unions = array($unions);
+ }
+ foreach ($unions as $i => $union) {
+ if ($union instanceof Query) {
+ $unions[$i] = $union->getSql($this->connection);
+ }
+ }
+ return "UNION (\n" . implode("\n) UNION (\n", $unions) . "\n)";
+ }
}