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.

517 lines
17 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;
/**
* QueryBuilder builds a SQL statement based on the specification given as a [[Query]] object.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class QueryBuilder extends \yii\base\Component
{
private $_connection;
13 years ago
public function __construct($connection)
13 years ago
{
$this->_connection = $connection;
}
/**
* @return CDbConnection the connection associated with this command
*/
public function getConnection()
{
return $this->_connection;
}
public function build($query)
{
$clauses = array(
13 years ago
$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),
13 years ago
);
return implode("\n", array_filter($clauses));
}
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.
* The {@link getColumnType} method will be invoked to convert any abstract type into a physical one.
*
* If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
* inserted into the generated SQL.
*
* @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();
foreach ($columns as $name => $type)
{
if (is_string($name))
$cols[] = "\t" . $this->quoteColumnName($name) . ' ' . $this->getColumnType($type);
else
$cols[] = "\t" . $type;
}
$sql = "CREATE TABLE " . $this->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
return $options === null ? $sql : $sql . ' ' . $options;
}
/**
* 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 $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)
{
return 'RENAME TABLE ' . $this->quoteTableName($table) . ' TO ' . $this->quoteTableName($newName);
}
/**
* 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)
{
return "DROP TABLE " . $this->quoteTableName($table);
}
/**
* 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);
}
/**
* 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.
* @param string $type the column type. The {@link 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 adding a new column.
* @since 1.1.6
*/
public function addColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->quoteTableName($table)
. ' ADD ' . $this->quoteColumnName($column) . ' '
. $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.
* @since 1.1.6
*/
public function dropColumn($table, $column)
{
return "ALTER TABLE " . $this->quoteTableName($table)
. " DROP COLUMN " . $this->quoteColumnName($column);
}
/**
* 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.
* @param string $name the old name of the column. The name will be properly quoted by the method.
* @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.
* @since 1.1.6
*/
public function renameColumn($table, $name, $newName)
{
return "ALTER TABLE " . $this->quoteTableName($table)
. " RENAME COLUMN " . $this->quoteColumnName($name)
. " TO " . $this->quoteColumnName($newName);
}
/**
* 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 {@link 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)
{
return 'ALTER TABLE ' . $this->quoteTableName($table) . ' CHANGE '
. $this->quoteColumnName($column) . ' '
. $this->quoteColumnName($column) . ' '
. $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.
* @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 $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 $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);
foreach ($columns as $i => $col)
$columns[$i] = $this->quoteColumnName($col);
$refColumns = preg_split('/\s*,\s*/', $refColumns, -1, PREG_SPLIT_NO_EMPTY);
foreach ($refColumns as $i => $col)
$refColumns[$i] = $this->quoteColumnName($col);
$sql = 'ALTER TABLE ' . $this->quoteTableName($table)
. ' ADD CONSTRAINT ' . $this->quoteColumnName($name)
. ' FOREIGN KEY (' . implode(', ', $columns) . ')'
. ' REFERENCES ' . $this->quoteTableName($refTable)
. ' (' . implode(', ', $refColumns) . ')';
if ($delete !== null)
$sql .= ' ON DELETE ' . $delete;
if ($update !== null)
$sql .= ' ON UPDATE ' . $update;
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)
{
return 'ALTER TABLE ' . $this->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->quoteColumnName($name);
}
/**
* 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 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)
{
$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->quoteColumnName($col);
}
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
. $this->quoteTableName($name) . ' ON '
. $this->quoteTableName($table) . ' (' . implode(', ', $cols) . ')';
}
/**
* 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)
{
return 'DROP INDEX ' . $this->quoteTableName($name) . ' ON ' . $this->quoteTableName($table);
}
protected function buildSelect($query)
{
$select = $query->distinct ? 'SELECT DISTINCT' : 'SELECT';
$columns = $query->select;
13 years ago
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) {
13 years ago
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-\.])$/', $column, $matches)) {
$columns[$i] = $this->_connection->quoteColumnName($matches[1]) . ' AS ' . $this->_connection->quoteSimpleColumnName($matches[2]);
13 years ago
}
else {
$columns[$i] = $this->_connection->quoteColumnName($column);
}
}
}
return $select . ' ' . implode(', ', $columns);
}
13 years ago
protected function buildFrom($query)
13 years ago
{
13 years ago
$tables = $query->from;
13 years ago
if (is_string($tables) && strpos($tables, '(') !== false) {
13 years ago
return 'FROM ' . $tables;
13 years ago
}
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) {
13 years ago
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias
13 years ago
$tables[$i] = $this->_connection->quoteTableName($matches[1]) . ' ' . $this->_connection->quoteTableName($matches[2]);
}
else {
$tables[$i] = $this->_connection->quoteTableName($table);
}
}
}
13 years ago
return 'FROM ' . implode(', ', $tables);
}
13 years ago
13 years ago
protected function buildJoin($query)
{
$joins = $query->join;
if (empty($joins)) {
return '';
}
if (is_string($joins)) {
return $joins;
}
13 years ago
13 years ago
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
$condition = $this->processCondition($join[2]);
$joins[$i] .= ' ON ' . $condition;
}
}
else {
throw new Exception('The join clause may be specified as an array of at least two elements.');
}
}
}
13 years ago
13 years ago
return implode("\n", $joins);
13 years ago
}
13 years ago
protected function buildWhere($query)
13 years ago
{
13 years ago
$where = $this->processConditions($query->where);
return empty($where) ? '' : 'WHERE ' . $where;
13 years ago
}
13 years ago
protected function buildGroupBy($query)
13 years ago
{
13 years ago
$columns = $query->groupBy;
if (empty($columns)) {
return '';
}
if (is_string($columns) && strpos($columns, '(') !== false) {
return 'GROUP BY ' . $columns;
}
13 years ago
13 years ago
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);
13 years ago
}
}
13 years ago
return 'GROUP BY ' . implode(', ', $columns);
13 years ago
}
13 years ago
protected function buildHaving($query)
13 years ago
{
13 years ago
$having = $this->processConditions($query->having);
return empty($having) ? '' : 'HAVING ' . $having;
13 years ago
}
13 years ago
protected function buildOrderBy($query)
13 years ago
{
13 years ago
$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);
13 years ago
}
}
}
13 years ago
return 'ORDER BY ' . implode(', ', $columns);
13 years ago
}
13 years ago
protected function buildLimit($query)
13 years ago
{
13 years ago
$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);
13 years ago
}
13 years ago
protected function buildUnion($query)
13 years ago
{
13 years ago
$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)";
13 years ago
}
13 years ago
protected function processCondition($conditions)
13 years ago
{
13 years ago
if (!is_array($conditions)) {
13 years ago
return $conditions;
13 years ago
}
elseif ($conditions === array()) {
13 years ago
return '';
13 years ago
}
13 years ago
$n = count($conditions);
$operator = strtoupper($conditions[0]);
13 years ago
if ($operator === 'OR' || $operator === 'AND') {
13 years ago
$parts = array();
13 years ago
for ($i = 1; $i < $n; ++$i) {
$condition = $this->processCondition($conditions[$i]);
if ($condition !== '') {
13 years ago
$parts[] = '(' . $condition . ')';
13 years ago
}
13 years ago
}
return $parts === array() ? '' : implode(' ' . $operator . ' ', $parts);
}
13 years ago
if (!isset($conditions[1], $conditions[2])) {
13 years ago
return '';
13 years ago
}
13 years ago
$column = $conditions[1];
13 years ago
if (strpos($column, '(') === false) {
13 years ago
$column = $this->_connection->quoteColumnName($column);
13 years ago
}
13 years ago
$values = $conditions[2];
13 years ago
if (!is_array($values)) {
13 years ago
$values = array($values);
13 years ago
}
13 years ago
13 years ago
if ($operator === 'IN' || $operator === 'NOT IN') {
if ($values === array()) {
13 years ago
return $operator === 'IN' ? '0=1' : '';
13 years ago
}
foreach ($values as $i => $value) {
if (is_string($value)) {
13 years ago
$values[$i] = $this->_connection->quoteValue($value);
13 years ago
}
else {
13 years ago
$values[$i] = (string)$value;
13 years ago
}
13 years ago
}
return $column . ' ' . $operator . ' (' . implode(', ', $values) . ')';
}
13 years ago
if ($operator === 'LIKE' || $operator === 'NOT LIKE' || $operator === 'OR LIKE' || $operator === 'OR NOT LIKE') {
if ($values === array()) {
13 years ago
return $operator === 'LIKE' || $operator === 'OR LIKE' ? '0=1' : '';
13 years ago
}
13 years ago
13 years ago
if ($operator === 'LIKE' || $operator === 'NOT LIKE') {
13 years ago
$andor = ' AND ';
13 years ago
}
else {
13 years ago
$andor = ' OR ';
$operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE';
}
$expressions = array();
13 years ago
foreach ($values as $value) {
13 years ago
$expressions[] = $column . ' ' . $operator . ' ' . $this->_connection->quoteValue($value);
13 years ago
}
13 years ago
return implode($andor, $expressions);
}
13 years ago
throw new Exception('Unknown operator: ' . $operator);
13 years ago
}
}