Class yii\db\mssql\QueryBuilder
| Inheritance | yii\ |
|---|---|
| Implements | yii\ |
| Available since version | 2.0 |
| Source Code | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/QueryBuilder.php |
QueryBuilder is the query builder for MS SQL Server databases (version 2019 and above).
Public Properties
| Property | Type | Description | Defined By |
|---|---|---|---|
| $db | yii\ |
The database connection. | yii\ |
| $separator | string | The separator between different fragments of a SQL statement. | yii\ |
| $typeMap | array | Mapping from abstract column types (keys) to physical column types (values). | yii\ |
Protected Properties
| Property | Type | Description | Defined By |
|---|---|---|---|
| $conditionClasses | array | Map of condition aliases to condition classes. | yii\ |
| $expressionBuilders | string[]|yii\ |
Maps expression class to expression builder class. | yii\ |
Public Methods
| Method | Description | Defined By |
|---|---|---|
| __call() | Calls the named method which is not a class method. | yii\ |
| __construct() | Constructor. | yii\ |
| __get() | Returns the value of an object property. | yii\ |
| __isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
| __set() | Sets value of an object property. | yii\ |
| __unset() | Sets an object property to null. | yii\ |
| addCheck() | Creates a SQL command for adding a check constraint to an existing table. | yii\ |
| addColumn() | Builds a SQL statement for adding a new DB column. | yii\ |
| addCommentOnColumn() | Builds a SQL command for adding comment to column. | yii\ |
| addCommentOnTable() | Builds a SQL command for adding comment to table. | yii\ |
| addDefaultValue() | Creates a SQL command for adding a default value constraint to an existing table. | yii\ |
| addForeignKey() | Builds a SQL statement for adding a foreign key constraint to an existing table. | yii\ |
| addPrimaryKey() | Builds a SQL statement for adding a primary key constraint to an existing table. | yii\ |
| addUnique() | Creates a SQL command for adding an unique constraint to an existing table. | yii\ |
| alterColumn() | Builds a SQL statement for changing the definition of a column. | yii\ |
| batchInsert() | Generates a batch INSERT SQL statement. | yii\ |
| bindParam() | Helper method to add $value to $params array using PARAM_PREFIX. | yii\ |
| build() | Generates a SELECT SQL statement from a yii\ |
yii\ |
| buildColumns() | Processes columns and properly quotes them if necessary. | yii\ |
| buildCondition() | Parses the condition specification and generates the corresponding SQL expression. | yii\ |
| buildExpression() | Builds given $expression | yii\ |
| buildFrom() | yii\ |
|
| buildGroupBy() | yii\ |
|
| buildHaving() | yii\ |
|
| buildJoin() | yii\ |
|
| buildLimit() | yii\ |
|
| buildOrderBy() | yii\ |
|
| buildOrderByAndLimit() | Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL. | yii\ |
| buildSelect() | yii\ |
|
| buildUnion() | yii\ |
|
| buildUnionOrderByAndLimit() | Builds the global ORDER BY and LIMIT/OFFSET clauses for a UNION query. | yii\ |
| buildWhere() | yii\ |
|
| buildWithQueries() | yii\ |
|
| canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
| canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
| checkIntegrity() | Builds a SQL statement for enabling or disabling integrity checks on table constraints. | yii\ |
| className() | Returns the fully qualified name of this class. | yii\ |
| createConditionFromArray() | Transforms $condition defined in array format (as described in yii\ |
yii\ |
| createIndex() | Builds a SQL statement for creating a new index. | yii\ |
| createTable() | Builds a SQL statement for creating a new DB table. | yii\ |
| createView() | Creates a SQL View. | yii\ |
| delete() | Creates a DELETE SQL statement. | yii\ |
| dropCheck() | Creates a SQL command for dropping a check constraint. | yii\ |
| dropColumn() | Drop all constraints before column delete. | yii\ |
| dropCommentFromColumn() | Builds a SQL command for adding comment to column. | yii\ |
| dropCommentFromTable() | Builds a SQL command for adding comment to table. | yii\ |
| dropDefaultValue() | Creates a SQL command for dropping a default value constraint. | yii\ |
| dropForeignKey() | Builds a SQL statement for dropping a foreign key constraint. | yii\ |
| dropIndex() | Builds a SQL statement for dropping an index. | yii\ |
| dropPrimaryKey() | Builds a SQL statement for removing a primary key constraint to an existing table. | yii\ |
| dropTable() | Builds a SQL statement for dropping a DB table. | yii\ |
| dropUnique() | Creates a SQL command for dropping an unique constraint. | yii\ |
| dropView() | Drops a SQL View. | yii\ |
| executeResetSequence() | Execute a SQL statement for resetting the sequence value of a table's primary key. | yii\ |
| getColumnType() | Converts an abstract column type into a physical column type. | yii\ |
| getExpressionBuilder() | Gets object of yii\ |
yii\ |
| hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
| hasProperty() | Returns a value indicating whether a property is defined. | yii\ |
| init() | Initializes the object. | yii\ |
| insert() | Creates an INSERT SQL statement. | yii\ |
| renameColumn() | Builds a SQL statement for renaming a column. | yii\ |
| renameTable() | Builds a SQL statement for renaming a DB table. | yii\ |
| resetSequence() | Creates a SQL statement for resetting the sequence value of a table's primary key. | yii\ |
| selectExists() | Creates a SELECT EXISTS() SQL statement. | yii\ |
| setConditionClasses() | Setter for $conditionClasses property. | yii\ |
| setExpressionBuilders() | Setter for $expressionBuilders property. | yii\ |
| truncateTable() | Builds a SQL statement for truncating a DB table. | yii\ |
| update() | Creates an UPDATE SQL statement. | yii\ |
| upsert() | Generates a MERGE statement that inserts a row or updates the matching one in a single atomic operation. |
yii\ |
Protected Methods
| Method | Description | Defined By |
|---|---|---|
| buildAddCommentSql() | Builds the SQL to add or update the MS_Description extended property of a table or column. |
yii\ |
| buildRemoveCommentSql() | Builds the SQL to remove the MS_Description extended property from a table or column. |
yii\ |
| concatUnionSql() | Concatenates the first SELECT statement with the UNION clauses built by {@see buildUnion()}. |
yii\ |
| defaultConditionClasses() | Contains array of default condition classes. Extend this method, if you want to change default condition classes for the query builder. See $conditionClasses docs for details. | yii\ |
| defaultExpressionBuilders() | Contains array of default expression builders. Extend this method and override it, if you want to change default expression builders for this query builder. See $expressionBuilders docs for details. | yii\ |
| extractAlias() | Extracts table alias if there is one or returns false | yii\ |
| hasLimit() | Checks to see if the given limit is effective. | yii\ |
| hasOffset() | Checks to see if the given offset is effective. | yii\ |
| prepareInsertSelectSubQuery() | Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement. | yii\ |
| prepareInsertValues() | Prepares a VALUES part for an INSERT SQL statement. |
yii\ |
| prepareSelectQuery() | Performs driver-specific preparation after yii\ |
yii\ |
| prepareUpdateSets() | Prepares a SET parts for an UPDATE SQL statement. |
yii\ |
| prepareUpsertColumns() | yii\ |
|
| prepareUpsertSets() | Prepares the SET assignments for the update branch of an upsert statement. |
yii\ |
Constants
| Constant | Value | Description | Defined By |
|---|---|---|---|
| PARAM_PREFIX | ':qp' | The prefix for automatically generated query binding parameters. | yii\ |
Property Details
Mapping from abstract column types (keys) to physical column types (values).
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
]
Method Details
Defined in:
yii\
Calls the named method which is not a class method.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
| public mixed __call ( string $name, array $params ) | ||
| $name | string |
The method name |
| $params | array |
Method parameters |
| return | mixed |
The method return value |
|---|---|---|
| throws | yii\ |
when calling unknown method |
public function __call($name, $params)
{
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in:
yii\
Constructor.
| public mixed __construct ( yii\ | ||
| $connection | yii\ |
The database connection. |
| $config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($connection, $config = [])
{
$this->db = $connection;
parent::__construct($config);
}
Defined in:
yii\
Returns the value of an object property.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $object->property;.
See also __set().
| public mixed __get ( string $name ) | ||
| $name | string |
The property name |
| return | mixed |
The property value |
|---|---|---|
| throws | yii\ |
if the property is not defined |
| throws | yii\ |
if the property is write-only |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
} elseif (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in:
yii\
Checks if a property is set, i.e. defined and not null.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($object->property).
Note that if the property is not defined, false will be returned.
| public boolean __isset ( string $name ) | ||
| $name | string |
The property name or the event name |
| return | boolean |
Whether the named property is set (not null). |
|---|---|---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
return false;
}
Defined in:
yii\
Sets value of an object property.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $object->property = $value;.
See also __get().
| public mixed __set ( string $name, mixed $value ) | ||
| $name | string |
The property name or the event name |
| $value | mixed |
The property value |
| throws | yii\ |
if the property is not defined |
|---|---|---|
| throws | yii\ |
if the property is read-only |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
}
Defined in:
yii\
Sets an object property to null.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($object->property).
Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.
| public mixed __unset ( string $name ) | ||
| $name | string |
The property name |
| throws | yii\ |
if the property is read only. |
|---|---|---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
}
}
Defined in:
yii\
Creates a SQL command for adding a check constraint to an existing table.
| public string addCheck ( string $name, string $table, string $expression ) | ||
| $name | string |
The name of the check constraint. The name will be properly quoted by the method. |
| $table | string |
The table that the check constraint will be added to. The name will be properly quoted by the method. |
| $expression | string |
The SQL of the |
| return | string |
The SQL statement for adding a check constraint to an existing table. |
|---|---|---|
public function addCheck($name, $table, $expression)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
. $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
}
Defined in:
yii\
Builds a SQL statement for adding a new DB column.
| public string addColumn ( string $table, string $column, string $type ) | ||
| $table | string |
The table that the new column will be added to. The table name will be properly quoted by the method. |
| $column | string |
The name of the new column. The name will be properly quoted by the method. |
| $type | string |
The 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 adding a new column. |
|---|---|---|
public function addColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD ' . $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
Builds a SQL command for adding comment to column.
| public string addCommentOnColumn ( mixed $table, mixed $column, mixed $comment ) | ||
| $table | mixed |
The table whose column is to be commented. The table name will be properly quoted by the method. |
| $column | mixed |
The name of the column to be commented. The column name will be properly quoted by the method. |
| $comment | mixed |
The text of the comment to be added. The comment will be properly quoted by the method. |
| return | string |
The SQL statement for adding comment on column |
|---|---|---|
public function addCommentOnColumn($table, $column, $comment)
{
return $this->buildAddCommentSql($comment, $table, $column);
}
Builds a SQL command for adding comment to table.
| public string addCommentOnTable ( mixed $table, mixed $comment ) | ||
| $table | mixed |
The table whose column is to be commented. The table name will be properly quoted by the method. |
| $comment | mixed |
The text of the comment to be added. The comment will be properly quoted by the method. |
| return | string |
The SQL statement for adding comment on table |
|---|---|---|
public function addCommentOnTable($table, $comment)
{
return $this->buildAddCommentSql($comment, $table);
}
Creates a SQL command for adding a default value constraint to an existing table.
| public string addDefaultValue ( mixed $name, mixed $table, mixed $column, mixed $value ) | ||
| $name | mixed |
The name of the default value constraint. The name will be properly quoted by the method. |
| $table | mixed |
The table that the default value constraint will be added to. The name will be properly quoted by the method. |
| $column | mixed |
The name of the column to that the constraint will be added on. The name will be properly quoted by the method. |
| $value | mixed |
Default value. |
| return | string |
The SQL statement for adding a default value constraint to an existing table. |
|---|---|---|
| throws | yii\ |
if this is not supported by the underlying DBMS. |
public function addDefaultValue($name, $table, $column, $value)
{
$tableName = $this->db->quoteTableName($table);
$constraintName = $this->db->quoteColumnName($name);
$defaultValue = match ($value) {
null => 'NULL',
false => '0',
true => '1',
default => (string) $this->db->quoteValue($value),
};
$columnName = $this->db->quoteColumnName($column);
return <<<SQL
ALTER TABLE {$tableName} ADD CONSTRAINT {$constraintName} DEFAULT {$defaultValue} FOR {$columnName}
SQL;
}
Defined in:
yii\
Builds a SQL statement for adding a foreign key constraint to an existing table.
The method will properly quote the table and column names.
| public string addForeignKey ( string $name, string $table, string|array $columns, string $refTable, string|array $refColumns, string|null $delete = null, string|null $update = null ) | ||
| $name | string |
The name of the foreign key constraint. |
| $table | string |
The table that the foreign key constraint will be added to. |
| $columns | string|array |
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. |
| $refTable | string |
The table that the foreign key references to. |
| $refColumns | string|array |
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. |
| $delete | string|null |
The ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL |
| $update | string|null |
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)
{
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
. ' REFERENCES ' . $this->db->quoteTableName($refTable)
. ' (' . $this->buildColumns($refColumns) . ')';
if ($delete !== null) {
$sql .= ' ON DELETE ' . $delete;
}
if ($update !== null) {
$sql .= ' ON UPDATE ' . $update;
}
return $sql;
}
Defined in:
yii\
Builds a SQL statement for adding a primary key constraint to an existing table.
| public string addPrimaryKey ( string $name, string $table, string|array $columns ) | ||
| $name | string |
The name of the primary key constraint. |
| $table | string |
The table that the primary key constraint will be added to. |
| $columns | string|array |
Comma separated string or array of columns that the primary key will consist of. |
| return | string |
The SQL statement for adding a primary key constraint to an existing table. |
|---|---|---|
public function addPrimaryKey($name, $table, $columns)
{
if (is_string($columns)) {
$columns = preg_split('/\s*,\s*/' , $columns, -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($columns as $i => $col) {
$columns[$i] = $this->db->quoteColumnName($col);
}
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
. $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
. implode(', ', $columns) . ')';
}
Defined in:
yii\
Creates a SQL command for adding an unique constraint to an existing table.
| public string addUnique ( string $name, string $table, string|array $columns ) | ||
| $name | string |
The name of the unique constraint. The name will be properly quoted by the method. |
| $table | string |
The table that the unique constraint will be added to. The name will be properly quoted by the method. |
| $columns | string|array |
The name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas. The name will be properly quoted by the method. |
| return | string |
The SQL statement for adding an unique constraint to an existing table. |
|---|---|---|
public function addUnique($name, $table, $columns)
{
if (is_string($columns)) {
$columns = preg_split('/\s*,\s*/' , $columns, -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($columns as $i => $col) {
$columns[$i] = $this->db->quoteColumnName($col);
}
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
. $this->db->quoteColumnName($name) . ' UNIQUE ('
. implode(', ', $columns) . ')';
}
Builds a SQL statement for changing the definition of a column.
Drops the default, check, and unique constraints attached to the column before the ALTER COLUMN statement,
because SQL Server rejects altering a column while such constraints are bound to it. Default, check, and unique
constraints defined by a {@see \
| public string alterColumn ( string $table, string $column, string $type ) | ||
| $table | string |
The table whose column is to be changed. The table name will be properly quoted by the method. |
| $column | string |
The name of the column to be changed. The name will be properly quoted by the method. |
| $type | string |
The new column type. The {@see \ |
| return | string |
The SQL statement for changing the definition of a column. |
|---|---|---|
| throws | yii\ |
if this is not supported by the underlying DBMS. |
public function alterColumn($table, $column, $type)
{
$tableName = $this->db->quoteTableName($table);
$columnName = $this->db->quoteColumnName($column);
$dropConstraintsSql = $this->dropConstraintsForColumn($tableName, $column, ['D', 'C', 'UQ']);
$sqlAfter = [];
$constraintBase = preg_replace('/[^a-z0-9_]/i', '', "{$table}_{$column}");
if ($type instanceof ColumnSchemaBuilder) {
$type->setAlterColumnFormat();
$defaultValue = $type->getDefaultValue();
if ($defaultValue !== null) {
$sqlAfter[] = $this->addDefaultValue(
"DF_{$constraintBase}",
$table,
$column,
$defaultValue instanceof Expression ? $defaultValue : new Expression($defaultValue),
);
}
$checkValue = $type->getCheckValue();
if ($checkValue !== null) {
$columnCheckConstraint = $this->db->quoteColumnName("CK_{$constraintBase}");
$checkSQL = $checkValue instanceof Expression ? $checkValue : new Expression($checkValue);
$sqlAfter[] = <<<SQL
ALTER TABLE {$tableName} ADD CONSTRAINT {$columnCheckConstraint} CHECK ({$checkSQL})
SQL;
}
if ($type->isUnique()) {
$columnUniqueConstraint = $this->db->quoteColumnName("UQ_{$constraintBase}");
$sqlAfter[] = <<<SQL
ALTER TABLE {$tableName} ADD CONSTRAINT {$columnUniqueConstraint} UNIQUE ({$columnName})
SQL;
}
}
$columnType = $this->getColumnType($type);
return implode(
"\n",
[
$dropConstraintsSql,
<<<SQL
ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$columnType}
SQL,
...$sqlAfter,
],
);
}
Defined in:
yii\
Generates a batch INSERT SQL statement.
For example,
$sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
]);
Note that the values in each row must match the corresponding column names.
The method will properly escape the column names, and quote the values to be inserted.
| public string batchInsert ( string $table, array $columns, array|Generator $rows, array &$params = [] ) | ||
| $table | string |
The table that new rows will be inserted into. |
| $columns | array |
The column names |
| $rows | array|Generator |
The rows to be batch inserted into the table |
| $params | array |
The binding parameters. This parameter exists since 2.0.14 |
| return | string |
The batch INSERT SQL statement |
|---|---|---|
public function batchInsert($table, $columns, $rows, &$params = [])
{
if (empty($rows)) {
return '';
}
$schema = $this->db->getSchema();
if (($tableSchema = $schema->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
} else {
$columnSchemas = [];
}
$values = [];
foreach ($rows as $row) {
$vs = [];
foreach ($row as $i => $value) {
if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
$value = $columnSchemas[$columns[$i]]->dbTypecast($value);
}
if (is_string($value)) {
$value = $schema->quoteValue($value);
} elseif (is_float($value)) {
// ensure type cast always has . as decimal separator in all locales
$value = StringHelper::floatToString($value);
} elseif ($value === false) {
$value = 0;
} elseif ($value === null) {
$value = 'NULL';
} elseif ($value instanceof ExpressionInterface) {
$value = $this->buildExpression($value, $params);
}
$vs[] = $value;
}
$values[] = '(' . implode(', ', $vs) . ')';
}
if (empty($values)) {
return '';
}
foreach ($columns as $i => $name) {
$columns[$i] = $schema->quoteColumnName($name);
}
return 'INSERT INTO ' . $schema->quoteTableName($table)
. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
}
Defined in:
yii\
Helper method to add $value to $params array using PARAM_PREFIX.
| public string bindParam ( string|null $value, array &$params ) | ||
| $value | string|null | |
| $params | array |
Passed by reference |
| return | string |
The placeholder name in $params array |
|---|---|---|
public function bindParam($value, &$params)
{
$phName = self::PARAM_PREFIX . count($params);
$params[$phName] = $value;
return $phName;
}
Defined in:
yii\
Generates a SELECT SQL statement from a yii\
| public array build ( yii\ | ||
| $query | yii\ |
The yii\ |
| $params | array |
The parameters to be bound to the generated SQL statement. These parameters will be included in the result with the additional parameters generated during the query building process. |
| 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). The parameters returned
include those provided in |
|---|---|---|
public function build($query, $params = [])
{
$query = $query->prepare($this);
$query = $this->prepareSelectQuery($query);
$params = empty($params) ? $query->params : array_merge($params, $query->params);
$clauses = [
$this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
$this->buildFrom($query->from, $params),
$this->buildJoin($query->join, $params),
$this->buildWhere($query->where, $params),
$this->buildGroupBy($query->groupBy),
$this->buildHaving($query->having, $params),
];
$sql = implode($this->separator, array_filter($clauses));
$sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
if (!empty($query->orderBy)) {
foreach ($query->orderBy as $expression) {
if ($expression instanceof ExpressionInterface) {
$this->buildExpression($expression, $params);
}
}
}
if (!empty($query->groupBy)) {
foreach ($query->groupBy as $expression) {
if ($expression instanceof ExpressionInterface) {
$this->buildExpression($expression, $params);
}
}
}
$union = $this->buildUnion($query->union, $params);
if ($union !== '') {
$sql = $this->concatUnionSql($sql, $union);
$sql = $this->buildUnionOrderByAndLimit(
$sql,
$query->unionOrderBy,
$query->unionLimit,
$query->unionOffset,
);
foreach ($query->unionOrderBy ?? [] as $expression) {
if ($expression instanceof ExpressionInterface) {
$this->buildExpression($expression, $params);
}
}
}
$with = $this->buildWithQueries($query->withQueries, $params);
if ($with !== '') {
$sql = "$with{$this->separator}$sql";
}
return [$sql, $params];
}
Builds the SQL to add or update the MS_Description extended property of a table or column.
Resolves the table name without loading metadata, so the statement is assembled without opening a database connection. The comment is added when the property is absent and updated otherwise, and the extended-property routines are qualified with the catalog when the name includes one.
| protected string buildAddCommentSql ( string $comment, string $table, string|null $column = null ) | ||
| $comment | string |
Comment text. Escaped and wrapped as an |
| $table | string |
Target table. May be 'catalog-', 'schema-', or bracket-qualified. |
| $column | string|null |
Target column, or |
| return | string |
SQL statement that adds or updates the comment. |
|---|---|---|
protected function buildAddCommentSql($comment, $table, $column = null)
{
[$catalog, $schemaLiteral, $tableLiteral, $listLevel2, $paramLevel2] = $this->resolveCommentParts(
$table,
$column,
);
$valueLiteral = "N'" . Quoter::escapeLiteralValue($comment) . "'";
return <<<SQL
IF NOT EXISTS (
SELECT 1
FROM {$catalog}sys.fn_listextendedproperty(
N'MS_Description',
'SCHEMA', {$schemaLiteral},
'TABLE', {$tableLiteral},
{$listLevel2}
)
)
EXEC {$catalog}sys.sp_addextendedproperty
@name = N'MS_Description',
@value = {$valueLiteral},
@level0type = 'SCHEMA', @level0name = {$schemaLiteral},
@level1type = 'TABLE', @level1name = {$tableLiteral}{$paramLevel2}
ELSE
EXEC {$catalog}sys.sp_updateextendedproperty
@name = N'MS_Description',
@value = {$valueLiteral},
@level0type = 'SCHEMA', @level0name = {$schemaLiteral},
@level1type = 'TABLE', @level1name = {$tableLiteral}{$paramLevel2}
SQL;
}
Defined in:
yii\
Processes columns and properly quotes them if necessary.
It will join all columns into a string with comma as separators.
| public string buildColumns ( string|array $columns ) | ||
| $columns | string|array |
The columns to be processed |
| return | string |
The processing result |
|---|---|---|
public function buildColumns($columns)
{
if (!is_array($columns)) {
if (strpos($columns, '(') !== false) {
return $columns;
}
$rawColumns = $columns;
$columns = preg_split('/\s*,\s*/' , $columns, -1, PREG_SPLIT_NO_EMPTY);
if ($columns === false) {
throw new InvalidArgumentException("$rawColumns is not valid columns.");
}
}
foreach ($columns as $i => $column) {
if ($column instanceof ExpressionInterface) {
$columns[$i] = $this->buildExpression($column);
} elseif (strpos($column, '(') === false) {
$columns[$i] = $this->db->quoteColumnName($column);
}
}
return implode(', ', $columns);
}
Defined in:
yii\
Parses the condition specification and generates the corresponding SQL expression.
| public string buildCondition ( string|array|yii\ | ||
| $condition | string|array|yii\ |
The condition specification. Please refer to yii\ |
| $params | array |
The binding parameters to be populated |
| return | string |
The generated SQL expression |
|---|---|---|
public function buildCondition($condition, &$params)
{
if (is_array($condition)) {
if (empty($condition)) {
return '';
}
$condition = $this->createConditionFromArray($condition);
}
if ($condition instanceof ExpressionInterface) {
return $this->buildExpression($condition, $params);
}
return (string)$condition;
}
| public string buildExpression ( yii\ | ||
| $expression | yii\ |
The expression to be built |
| $params | array |
The parameters to be bound to the generated SQL statement. These parameters will be included in the result with the additional parameters generated during the expression building process. |
| return | string |
The SQL statement that will not be neither quoted nor encoded before passing to DBMS |
|---|---|---|
| throws | yii\ |
when $expression building is not supported by this QueryBuilder. |
public function buildExpression(ExpressionInterface $expression, &$params = [])
{
$builder = $this->getExpressionBuilder($expression);
return $builder->build($expression, $params);
}
Defined in:
yii\
| public string buildFrom ( array $tables, array &$params ) | ||
| $tables | array | |
| $params | array |
The binding parameters to be populated |
| return | string |
The FROM clause built from yii\ |
|---|---|---|
public function buildFrom($tables, &$params)
{
if (empty($tables)) {
return '';
}
$tables = $this->quoteTableNames($tables, $params);
return 'FROM ' . implode(', ', $tables);
}
Defined in:
yii\
| public string buildGroupBy ( array $columns ) | ||
| $columns | array | |
| return | string |
The GROUP BY clause |
|---|---|---|
public function buildGroupBy($columns)
{
if (empty($columns)) {
return '';
}
foreach ($columns as $i => $column) {
if ($column instanceof ExpressionInterface) {
$columns[$i] = $this->buildExpression($column);
} elseif (strpos($column, '(') === false) {
$columns[$i] = $this->db->quoteColumnName($column);
}
}
return 'GROUP BY ' . implode(', ', $columns);
}
Defined in:
yii\
| public string buildHaving ( string|array $condition, array &$params ) | ||
| $condition | string|array | |
| $params | array |
The binding parameters to be populated |
| return | string |
The HAVING clause built from yii\ |
|---|---|---|
public function buildHaving($condition, &$params)
{
$having = $this->buildCondition($condition, $params);
return $having === '' ? '' : 'HAVING ' . $having;
}
Defined in:
yii\
| public string buildJoin ( array $joins, array &$params ) | ||
| $joins | array | |
| $params | array |
The binding parameters to be populated |
| return | string |
The JOIN clause built from yii\ |
|---|---|---|
| throws | yii\ |
if the $joins parameter is not in proper format |
public function buildJoin($joins, &$params)
{
if (empty($joins)) {
return '';
}
foreach ($joins as $i => $join) {
if (!is_array($join) || !isset($join[0], $join[1])) {
throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
}
// 0:join type, 1:join table, 2:on-condition (optional)
list($joinType, $table) = $join;
$tables = $this->quoteTableNames((array)$table, $params);
$table = reset($tables);
$joins[$i] = "$joinType $table";
if (isset($join[2])) {
$condition = $this->buildCondition($join[2], $params);
if ($condition !== '') {
$joins[$i] .= ' ON ' . $condition;
}
}
}
return implode($this->separator, $joins);
}
Defined in:
yii\
| public string buildLimit ( integer $limit, integer $offset ) | ||
| $limit | integer | |
| $offset | integer | |
| return | string |
The LIMIT and OFFSET clauses |
|---|---|---|
public function buildLimit($limit, $offset)
{
$sql = '';
if ($this->hasLimit($limit)) {
$sql = 'LIMIT ' . $limit;
}
if ($this->hasOffset($offset)) {
$sql .= ' OFFSET ' . $offset;
}
return ltrim($sql);
}
Defined in:
yii\
| public string buildOrderBy ( array $columns ) | ||
| $columns | array | |
| return | string |
The ORDER BY clause built from yii\ |
|---|---|---|
public function buildOrderBy($columns)
{
if (empty($columns)) {
return '';
}
$orders = [];
foreach ($columns as $name => $direction) {
if ($direction instanceof ExpressionInterface) {
$orders[] = $this->buildExpression($direction);
} else {
$orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
}
}
return 'ORDER BY ' . implode(', ', $orders);
}
Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
| public string buildOrderByAndLimit ( mixed $sql, mixed $orderBy, mixed $limit, mixed $offset ) | ||
| $sql | mixed |
The existing SQL (without ORDER BY/LIMIT/OFFSET) |
| $orderBy | mixed |
The order by columns. See yii\ |
| $limit | mixed |
The limit number. See yii\ |
| $offset | mixed |
The offset number. See yii\ |
| return | string |
The SQL completed with ORDER BY/LIMIT/OFFSET (if any) |
|---|---|---|
public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
{
// SQL Server requires `FETCH` to be greater than zero. Use `TOP (0)` on the original `SELECT` to avoid
// derived-table column-name requirements for unnamed or duplicate expressions.
if ($this->isZeroLimit($limit)) {
return $this->addTopZero($sql);
}
$orderBy = $this->buildOrderBy($orderBy);
if (!$this->hasOffset($offset) && !$this->hasLimit($limit)) {
return $orderBy === '' ? $sql : "{$sql}{$this->separator}{$orderBy}";
}
if ($orderBy === '') {
// SELECT DISTINCT requires ORDER BY items to appear in the select list, so use ordinal `1`;
// otherwise `ORDER BY (SELECT NULL)` is preferred because it tolerates unorderable column types
// (`text`, `ntext`, `image`, `xml`, `geography`, `geometry`) which `ORDER BY 1` cannot sort.
$orderBy = str_starts_with($sql, 'SELECT DISTINCT')
? 'ORDER BY 1'
: 'ORDER BY (SELECT NULL)';
}
$offset = $this->hasOffset($offset) ? $offset : 0;
$sql .= "{$this->separator}{$orderBy}{$this->separator}OFFSET {$offset} ROWS";
if ($this->hasLimit($limit)) {
$sql .= "{$this->separator}FETCH NEXT {$limit} ROWS ONLY";
}
return $sql;
}
Builds the SQL to remove the MS_Description extended property from a table or column.
Resolves the table name without loading metadata, so the statement is assembled without opening a database connection. The property is dropped only when present, and the extended-property routines are qualified with the catalog when the name includes one.
| protected string buildRemoveCommentSql ( string $table, string|null $column = null ) | ||
| $table | string |
Target table. May be 'catalog-', 'schema-', or bracket-qualified. |
| $column | string|null |
Target column, or |
| return | string |
SQL statement that removes the comment. |
|---|---|---|
protected function buildRemoveCommentSql($table, $column = null)
{
[$catalog, $schemaLiteral, $tableLiteral, $listLevel2, $paramLevel2] = $this->resolveCommentParts(
$table,
$column,
);
return <<<SQL
IF EXISTS (
SELECT 1
FROM {$catalog}sys.fn_listextendedproperty(
N'MS_Description',
'SCHEMA', {$schemaLiteral},
'TABLE', {$tableLiteral},
{$listLevel2}
)
)
EXEC {$catalog}sys.sp_dropextendedproperty
@name = N'MS_Description',
@level0type = 'SCHEMA', @level0name = {$schemaLiteral},
@level1type = 'TABLE', @level1name = {$tableLiteral}{$paramLevel2}
SQL;
}
Defined in:
yii\
| public string buildSelect ( array $columns, array &$params, boolean $distinct = false, string|null $selectOption = null ) | ||
| $columns | array | |
| $params | array |
The binding parameters to be populated |
| $distinct | boolean | |
| $selectOption | string|null | |
| return | string |
The SELECT clause built from yii\ |
|---|---|---|
public function buildSelect($columns, &$params, $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 ($column instanceof ExpressionInterface) {
if (is_int($i)) {
$columns[$i] = $this->buildExpression($column, $params);
} else {
$columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
}
} elseif ($column instanceof Query) {
list($sql, $params) = $this->build($column, $params);
$columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
} elseif (is_string($i) && $i !== $column) {
if (strpos($column, '(') === false) {
$column = $this->db->quoteColumnName($column);
}
$columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
} 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);
}
}
}
return $select . ' ' . implode(', ', $columns);
}
Defined in:
yii\
| public string buildUnion ( array $unions, array &$params ) | ||
| $unions | array | |
| $params | array |
The binding parameters to be populated |
| return | string |
The UNION clause built from yii\ |
|---|---|---|
public function buildUnion($unions, &$params)
{
if (empty($unions)) {
return '';
}
$result = '';
foreach ($unions as $i => $union) {
$query = $union['query'];
if ($query instanceof Query) {
list($unions[$i]['query'], $params) = $this->build($query, $params);
}
$result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
}
return trim($result);
}
Builds the global ORDER BY and LIMIT/OFFSET clauses for a UNION query.
| public string buildUnionOrderByAndLimit ( string $sql, array|null $orderBy, integer|yii\ | ||
| $sql | string |
The complete UNION SQL without global ORDER BY/LIMIT/OFFSET clauses. |
| $orderBy | array|null |
The global order by columns. |
| $limit | integer|yii\ |
The global limit. |
| $offset | integer|yii\ |
The global offset. |
| return | string |
The completed UNION SQL. |
|---|---|---|
public function buildUnionOrderByAndLimit(
string $sql,
array|null $orderBy,
int|ExpressionInterface|null $limit,
int|ExpressionInterface|null $offset,
): string {
if (($orderBy === null || $orderBy === []) && ($this->hasOffset($offset) || $this->hasLimit($limit))) {
// SQL Server requires ORDER BY for OFFSET/FETCH. Unlike a plain SELECT, a UNION only permits selected
// columns in ORDER BY, so use the first result column rather than `ORDER BY (SELECT NULL)`.
$orderBy = [new Expression('1')];
}
return parent::buildUnionOrderByAndLimit($sql, $orderBy, $limit, $offset);
}
Defined in:
yii\
| public string buildWhere ( string|array $condition, array &$params ) | ||
| $condition | string|array | |
| $params | array |
The binding parameters to be populated |
| return | string |
The WHERE clause built from yii\ |
|---|---|---|
public function buildWhere($condition, &$params)
{
$where = $this->buildCondition($condition, $params);
return $where === '' ? '' : 'WHERE ' . $where;
}
SQL Server does not support the RECURSIVE keyword for CTEs. Recursion is implicit when a CTE references itself.
| public string buildWithQueries ( mixed $withs, mixed &$params ) | ||
| $withs | mixed |
Of configurations for each WITH query |
| $params | mixed |
The binding parameters to be populated |
| return | string |
Compiled WITH prefix of query including nested queries |
|---|---|---|
public function buildWithQueries($withs, &$params)
{
if ($withs === null || $withs === []) {
return '';
}
foreach ($withs as $i => $with) {
$with['recursive'] = false;
$withs[$i] = $with;
}
return parent::buildWithQueries($withs, $params);
}
Defined in:
yii\
Returns a value indicating whether a property can be read.
A property is readable if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVarsis true);
See also canSetProperty().
| public boolean canGetProperty ( string $name, boolean $checkVars = true ) | ||
| $name | string |
The property name |
| $checkVars | boolean |
Whether to treat member variables as properties |
| return | boolean |
Whether the property can be read |
|---|---|---|
public function canGetProperty($name, $checkVars = true)
{
return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}
Defined in:
yii\
Returns a value indicating whether a property can be set.
A property is writable if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVarsis true);
See also canGetProperty().
| public boolean canSetProperty ( string $name, boolean $checkVars = true ) | ||
| $name | string |
The property name |
| $checkVars | boolean |
Whether to treat member variables as properties |
| return | boolean |
Whether the property can be written |
|---|---|---|
public function canSetProperty($name, $checkVars = true)
{
return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}
Builds a SQL statement for enabling or disabling integrity checks on table constraints.
Resolves the table and schema names without loading metadata, so the statement is built without opening a
database connection. A single table yields a direct ALTER TABLE statement; an empty table targets every base
table in the schema, enumerated server-side from sys.tables (views excluded) and run in one batch.
Enabling uses WITH CHECK CHECK CONSTRAINT ALL, re-validating existing rows and marking the constraints trusted;
disabling uses NOCHECK CONSTRAINT ALL.
See also:
| public string checkIntegrity ( boolean $check = true, string $schema = '', string $table = '' ) | ||
| $check | boolean |
Whether to enable ( |
| $schema | string |
The schema of the tables. Defaults to an empty string, meaning the default schema. |
| $table | string |
The table name. Defaults to an empty string, meaning every table in the schema. |
| return | string |
The SQL statement for enabling or disabling the integrity checks. |
|---|---|---|
public function checkIntegrity($check = true, $schema = '', $table = '')
{
$constraintCheck = $check ? 'WITH CHECK CHECK' : 'NOCHECK';
if ($table !== '') {
$tableName = $this->db->quoteTableName($schema === '' ? $table : "{$schema}.{$table}");
return <<<SQL
ALTER TABLE {$tableName} {$constraintCheck} CONSTRAINT ALL
SQL;
}
/** @var Schema $dbSchema */
$dbSchema = $this->db->getSchema();
[$catalogName, $schemaName] = $dbSchema->resolveRawCatalogSchemaName($schema);
$systemCatalog = $dbSchema->quoteSystemCatalogName($catalogName);
$catalogNameLiteral = $catalogName === null ? 'NULL' : "N'" . Quoter::escapeLiteralValue($catalogName) . "'";
$schemaNameLiteral = "N'" . Quoter::escapeLiteralValue($schemaName) . "'";
return <<<SQL
DECLARE @catalogName SYSNAME = {$catalogNameLiteral}
DECLARE @schemaName SYSNAME = {$schemaNameLiteral}
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = STRING_AGG(
CONVERT(
NVARCHAR(MAX),
N'ALTER TABLE '
+ COALESCE(QUOTENAME(@catalogName) + N'.', N'')
+ QUOTENAME(@schemaName)
+ N'.'
+ QUOTENAME([t].[name])
+ N' {$constraintCheck} CONSTRAINT ALL'
),
N'; '
)
FROM {$systemCatalog}.[tables] AS [t]
INNER JOIN {$systemCatalog}.[schemas] AS [s] ON [s].[schema_id] = [t].[schema_id]
WHERE [s].[name] = @schemaName
IF @sql IS NOT NULL
EXEC (@sql)
SQL;
}
Defined in:
yii\
Returns the fully qualified name of this class.
| public static string className ( ) | ||
| return | string |
The fully qualified name of this class. |
|---|---|---|
public static function className(): string
{
return static::class;
}
Defined in:
yii\
Concatenates the first SELECT statement with the UNION clauses built by {@see buildUnion()}.
| protected string concatUnionSql ( string $sql, string $union ) | ||
| $sql | string |
The SQL of the first |
| $union | string |
The UNION clauses. |
| return | string |
The compound SQL with the first statement parenthesized. |
|---|---|---|
protected function concatUnionSql(string $sql, string $union): string
{
return "($sql){$this->separator}$union";
}
Defined in:
yii\
Transforms $condition defined in array format (as described in yii\
See also $conditionClasses.
| public yii\ | ||
| $condition | string|array | |
public function createConditionFromArray($condition)
{
if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
$operator = strtoupper(array_shift($condition));
if (isset($this->conditionClasses[$operator])) {
$className = $this->conditionClasses[$operator];
} else {
$className = 'yii\db\conditions\SimpleCondition' ;
}
/** @var ConditionInterface $className */
return $className::fromArrayDefinition($operator, $condition);
}
// hash format: 'column1' => 'value1', 'column2' => 'value2', ...
return new HashCondition($condition);
}
Defined in:
yii\
Builds a SQL statement for creating a new index.
| public string createIndex ( string $name, string $table, string|array $columns, boolean $unique = false ) | ||
| $name | string |
The name of the index. The name will be properly quoted by the method. |
| $table | string |
The table that the new index will be created for. The table name will be properly quoted by the method. |
| $columns | string|array |
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. |
| $unique | boolean |
Whether to add UNIQUE constraint on the created index. |
| return | string |
The SQL statement for creating a new index. |
|---|---|---|
public function createIndex($name, $table, $columns, $unique = false)
{
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
. $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table)
. ' (' . $this->buildColumns($columns) . ')';
}
Defined in:
yii\
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 must contain an abstract DB type. The 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.
For example,
$sql = $queryBuilder->createTable('user', [
'id' => 'pk',
'name' => 'string',
'age' => 'integer',
'column_name double precision null default null', # definition only example
]);
| public string createTable ( string $table, array $columns, string|null $options = null ) | ||
| $table | string |
The name of the table to be created. The name will be properly quoted by the method. |
| $columns | array |
The columns (name => definition) in the new table. |
| $options | string|null |
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 = [];
foreach ($columns as $name => $type) {
if (is_string($name)) {
$cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
} else {
$cols[] = "\t" . $type;
}
}
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n" , $cols) . "\n)" ;
return $options === null ? $sql : $sql . ' ' . $options;
}
Defined in:
yii\
Creates a SQL View.
| public string createView ( string $viewName, string|yii\ | ||
| $viewName | string |
The name of the view to be created. |
| $subQuery | string|yii\ |
The select statement which defines the view.
This can be either a string or a yii\ |
| return | string |
The |
|---|---|---|
public function createView($viewName, $subQuery)
{
if ($subQuery instanceof Query) {
list($rawQuery, $params) = $this->build($subQuery);
array_walk(
$params,
function (&$param) {
$param = $this->db->quoteValue($param);
}
);
$subQuery = strtr($rawQuery, $params);
}
return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
}
Defined in:
yii\
Contains array of default condition classes. Extend this method, if you want to change default condition classes for the query builder. See $conditionClasses docs for details.
See also $conditionClasses.
| protected array defaultConditionClasses ( ) |
protected function defaultConditionClasses()
{
return [
'NOT' => 'yii\db\conditions\NotCondition' ,
'AND' => 'yii\db\conditions\AndCondition' ,
'OR' => 'yii\db\conditions\OrCondition' ,
'BETWEEN' => 'yii\db\conditions\BetweenCondition' ,
'NOT BETWEEN' => 'yii\db\conditions\BetweenCondition' ,
'IN' => 'yii\db\conditions\InCondition' ,
'NOT IN' => 'yii\db\conditions\InCondition' ,
'LIKE' => 'yii\db\conditions\LikeCondition' ,
'NOT LIKE' => 'yii\db\conditions\LikeCondition' ,
'OR LIKE' => 'yii\db\conditions\LikeCondition' ,
'OR NOT LIKE' => 'yii\db\conditions\LikeCondition' ,
'EXISTS' => 'yii\db\conditions\ExistsCondition' ,
'NOT EXISTS' => 'yii\db\conditions\ExistsCondition' ,
];
}
Contains array of default expression builders. Extend this method and override it, if you want to change default expression builders for this query builder. See $expressionBuilders docs for details.
| protected array defaultExpressionBuilders ( ) |
protected function defaultExpressionBuilders()
{
return [
...parent::defaultExpressionBuilders(),
InCondition::class => conditions\InConditionBuilder::class,
LikeCondition::class => conditions\LikeConditionBuilder::class,
];
}
Creates a DELETE SQL statement.
Renders any rowversion in the WHERE condition as a binary literal, enabling optimistic-lock deletes.
For example,
$sql = $queryBuilder->delete('user', 'status = 0');
The method will properly escape the table and column names.
| public string delete ( mixed $table, mixed $condition, mixed &$params ) | ||
| $table | mixed |
The table where the data will be deleted from. |
| $condition | mixed |
The condition that will be put in the WHERE part. Please
refer to yii\ |
| $params | mixed |
The binding parameters that will be modified by this method so that they can be bound to the DB command later. |
| return | string |
The DELETE SQL |
|---|---|---|
public function delete($table, $condition, &$params)
{
$schema = $this->db->getTableSchema($table);
if ($schema !== null) {
$condition = $this->castRowVersionConditions($schema, $condition);
}
return parent::delete($table, $condition, $params);
}
Defined in:
yii\
Creates a SQL command for dropping a check constraint.
| public string dropCheck ( string $name, string $table ) | ||
| $name | string |
The name of the check constraint to be dropped. The name will be properly quoted by the method. |
| $table | string |
The table whose check constraint is to be dropped. The name will be properly quoted by the method. |
| return | string |
The SQL statement for dropping a check constraint. |
|---|---|---|
public function dropCheck($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
Drop all constraints before column delete.
{@inheritdoc}
| public mixed dropColumn ( mixed $table, mixed $column ) | ||
| $table | mixed | |
| $column | mixed | |
public function dropColumn($table, $column)
{
$tableName = $this->db->quoteTableName($table);
$columnName = $this->db->quoteColumnName($column);
$dropConstraintsSql = $this->dropConstraintsForColumn($tableName, $column);
return <<<SQL
{$dropConstraintsSql}
ALTER TABLE {$tableName} DROP COLUMN {$columnName}
SQL;
}
Builds a SQL command for adding comment to column.
| public string dropCommentFromColumn ( mixed $table, mixed $column ) | ||
| $table | mixed |
The table whose column is to be commented. The table name will be properly quoted by the method. |
| $column | mixed |
The name of the column to be commented. The column name will be properly quoted by the method. |
| return | string |
The SQL statement for adding comment on column |
|---|---|---|
public function dropCommentFromColumn($table, $column)
{
return $this->buildRemoveCommentSql($table, $column);
}
Builds a SQL command for adding comment to table.
| public string dropCommentFromTable ( mixed $table ) | ||
| $table | mixed |
The table whose column is to be commented. The table name will be properly quoted by the method. |
| return | string |
The SQL statement for adding comment on column |
|---|---|---|
public function dropCommentFromTable($table)
{
return $this->buildRemoveCommentSql($table);
}
Creates a SQL command for dropping a default value constraint.
See also:
| public string dropDefaultValue ( mixed $name, mixed $table ) | ||
| $name | mixed |
The name of the default value constraint to be dropped. The name will be properly quoted by the method. |
| $table | mixed |
The table whose default value constraint is to be dropped. The name will be properly quoted by the method. |
| return | string |
The SQL statement for dropping a default value constraint. |
|---|---|---|
| throws | yii\ |
if this is not supported by the underlying DBMS. |
public function dropDefaultValue($name, $table)
{
$tableName = Quoter::escapeLiteralValue($this->db->quoteTableName($table));
$constraintName = Quoter::escapeLiteralValue($name);
return <<<SQL
DECLARE @tableName NVARCHAR(MAX) = N'{$tableName}'
DECLARE @constraintName SYSNAME = N'{$constraintName}'
DECLARE @dropSql NVARCHAR(MAX)
SELECT @dropSql = N'ALTER TABLE ' + @tableName + N' DROP CONSTRAINT ' + QUOTENAME([dc].[name])
FROM [sys].[default_constraints] AS [dc]
WHERE [dc].[parent_object_id] = OBJECT_ID(@tableName, N'U')
AND [dc].[name] = @constraintName
IF @dropSql IS NULL
BEGIN
THROW 50000, 'Default constraint not found on table.', 1;
END
EXEC (@dropSql)
SQL;
}
Defined in:
yii\
Builds a SQL statement for dropping a foreign key constraint.
| public string dropForeignKey ( string $name, string $table ) | ||
| $name | string |
The name of the foreign key constraint to be dropped. The name will be properly quoted by the method. |
| $table | string |
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->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
Defined in:
yii\
Builds a SQL statement for dropping an index.
| public string dropIndex ( string $name, string $table ) | ||
| $name | string |
The name of the index to be dropped. The name will be properly quoted by the method. |
| $table | string |
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->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
}
Defined in:
yii\
Builds a SQL statement for removing a primary key constraint to an existing table.
| public string dropPrimaryKey ( string $name, string $table ) | ||
| $name | string |
The name of the primary key constraint to be removed. |
| $table | string |
The table that the primary key constraint will be removed from. |
| return | string |
The SQL statement for removing a primary key constraint from an existing table. |
|---|---|---|
public function dropPrimaryKey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
Defined in:
yii\
Builds a SQL statement for dropping a DB table.
| public string dropTable ( string $table ) | ||
| $table | string |
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->db->quoteTableName($table);
}
Defined in:
yii\
Creates a SQL command for dropping an unique constraint.
| public string dropUnique ( string $name, string $table ) | ||
| $name | string |
The name of the unique constraint to be dropped. The name will be properly quoted by the method. |
| $table | string |
The table whose unique constraint is to be dropped. The name will be properly quoted by the method. |
| return | string |
The SQL statement for dropping an unique constraint. |
|---|---|---|
public function dropUnique($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
Defined in:
yii\
Drops a SQL View.
| public string dropView ( string $viewName ) | ||
| $viewName | string |
The name of the view to be dropped. |
| return | string |
The |
|---|---|---|
public function dropView($viewName)
{
return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
}
Defined in:
yii\
Execute a SQL statement for resetting the sequence value of a table's primary key.
Reason for execute is that some databases (Oracle) need several queries to do so.
The sequence is reset such that the primary key of the next new row inserted will have the specified value or the
maximum existing value +1.
| public mixed executeResetSequence ( string $table, integer|null $value = null ) | ||
| $table | string |
The name of the table whose primary key sequence is reset. |
| $value | integer|null |
The integer 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 the maximum existing value |
| throws | yii\ |
if this is not supported by the underlying DBMS |
|---|---|---|
public function executeResetSequence($table, $value = null)
{
$this->db->createCommand()->resetSequence($table, $value)->execute();
}
Extracts table alias if there is one or returns false
| protected boolean|array extractAlias ( mixed $table ) | ||
| $table | mixed | |
protected function extractAlias($table)
{
if (Quoter::isIdentifierBracketQuoted($table)) {
return false;
}
return parent::extractAlias($table);
}
Converts an abstract column type into a physical column type.
The conversion is done using the type map specified in $typeMap. 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"bigpk: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"upk: an unsigned auto-incremental primary key type, will be converted into "int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY"char: char type, will be converted into "char(1)"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 converted result. For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
For some of the abstract types you can also specify a length or precision constraint
by appending it in round brackets directly to the type.
For example string(32) will be converted into "varchar(32)" on a MySQL database.
If the underlying DBMS does not support these kind of constraints for a type it will
be ignored.
If a type cannot be found in $typeMap, it will be returned without any change.
| public string getColumnType ( mixed $type ) | ||
| $type | mixed |
Abstract column type |
| return | string |
Physical column type. |
|---|---|---|
public function getColumnType($type)
{
$columnType = parent::getColumnType($type);
// remove unsupported keywords
$columnType = preg_replace("/\s*comment '.*'/i" , '', $columnType);
$columnType = preg_replace('/ first$/i', '', $columnType);
return $columnType;
}
Defined in:
yii\
Gets object of yii\
Uses $expressionBuilders array to find a suitable builder class.
See also $expressionBuilders.
| public yii\ | ||
| $expression | yii\ |
|
| throws | yii\ |
when $expression building is not supported by this QueryBuilder. |
|---|---|---|
public function getExpressionBuilder(ExpressionInterface $expression)
{
$className = get_class($expression);
if (!isset($this->expressionBuilders[$className])) {
foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
if (is_subclass_of($expression, $expressionClass)) {
$this->expressionBuilders[$className] = $builderClass;
break;
}
}
if (!isset($this->expressionBuilders[$className])) {
throw new InvalidArgumentException('Expression of class ' . $className . ' can not be built in ' . get_class($this));
}
}
if ($this->expressionBuilders[$className] === __CLASS__) {
/** @var $this&ExpressionBuilderInterface $result */
$result = $this;
return $result;
}
if (!is_object($this->expressionBuilders[$className])) {
$this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
}
return $this->expressionBuilders[$className];
}
Defined in:
yii\
Checks to see if the given limit is effective.
| protected boolean hasLimit ( mixed $limit ) | ||
| $limit | mixed |
The given limit |
| return | boolean |
Whether the limit is effective |
|---|---|---|
protected function hasLimit($limit)
{
return ($limit instanceof ExpressionInterface) || ctype_digit((string)$limit);
}
Defined in:
yii\
Returns a value indicating whether a method is defined.
The default implementation is a call to php function method_exists().
You may override this method when you implemented the php magic method __call().
| public boolean hasMethod ( string $name ) | ||
| $name | string |
The method name |
| return | boolean |
Whether the method is defined |
|---|---|---|
public function hasMethod($name)
{
return method_exists($this, $name);
}
Defined in:
yii\
Checks to see if the given offset is effective.
| protected boolean hasOffset ( mixed $offset ) | ||
| $offset | mixed |
The given offset |
| return | boolean |
Whether the offset is effective |
|---|---|---|
protected function hasOffset($offset)
{
return ($offset instanceof ExpressionInterface) || ctype_digit((string)$offset) && (string)$offset !== '0';
}
Defined in:
yii\
Returns a value indicating whether a property is defined.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVarsis true);
See also:
| public boolean hasProperty ( string $name, boolean $checkVars = true ) | ||
| $name | string |
The property name |
| $checkVars | boolean |
Whether to treat member variables as properties |
| return | boolean |
Whether the property is defined |
|---|---|---|
public function hasProperty($name, $checkVars = true)
{
return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}
Defined in:
yii\
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
| public mixed init ( ) |
public function init()
{
parent::init();
$this->expressionBuilders = array_merge($this->defaultExpressionBuilders(), $this->expressionBuilders);
$this->conditionClasses = array_merge($this->defaultConditionClasses(), $this->conditionClasses);
}
Creates an INSERT SQL statement.
Wraps the INSERT with an OUTPUT INSERTED.* INTO @temporary_inserted block so that the inserted row
(including computed columns and IDENTITY values) can be retrieved by the caller.
For example,
`
$sql = $queryBuilder->insert('user', [
'name' => 'Sam',
'age' => 30,
], $params);
`
The method will properly escape the table and column names.
| public string insert ( mixed $table, mixed $columns, mixed &$params ) | ||
| $table | mixed |
The table that new rows will be inserted into. |
| $columns | mixed |
The column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO ... SELECT SQL statement. Passing of Query is available since version 2.0.11. |
| $params | mixed |
The binding parameters that will be generated by this method. They should be bound to the DB command later. |
| return | string |
The INSERT SQL |
|---|---|---|
public function insert($table, $columns, &$params)
{
$schema = $this->db->getTableSchema($table);
if ($schema === null) {
throw new InvalidArgumentException("Table not found: {$table}");
}
[$names, $placeholders, $values, $params] = $this->prepareInsertValues(
$table,
$columns,
$params,
);
$cols = [];
$outputColumns = [];
foreach ($schema->columns as $column) {
if (!$column instanceof ColumnSchema || $column->isComputed) {
continue;
}
$quoteColumnName = $this->db->quoteColumnName($column->name);
$cols[] = "{$quoteColumnName} {$column->getOutputColumnDeclaration()} " . ($column->allowNull ? 'NULL' : '');
$outputColumns[] = "INSERTED.{$quoteColumnName}";
}
$countColumns = count($outputColumns);
$sql = 'INSERT INTO ' . $this->db->quoteTableName($table)
. (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
. ($countColumns ? ' OUTPUT ' . implode(',', $outputColumns) . ' INTO @temporary_inserted' : '')
. (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
if ($countColumns) {
$tempTableCols = implode(', ', $cols);
$sql = <<<SQL
SET NOCOUNT ON;DECLARE @temporary_inserted TABLE ({$tempTableCols});{$sql};SELECT * FROM @temporary_inserted
SQL;
}
return $sql;
}
Defined in:
yii\
Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
| protected array prepareInsertSelectSubQuery ( yii\ | ||
| $columns | yii\ |
Object, which represents select query. |
| $schema | yii\ |
Schema object to quote column name. |
| $params | array |
The parameters to be bound to the generated SQL statement. These parameters will be included in the result with the additional parameters generated during the query building process. |
| return | array |
Array of column names, values and params. |
|---|---|---|
| throws | yii\ |
if query's select does not contain named parameters only. |
protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
{
if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
}
list($values, $params) = $this->build($columns, $params);
$names = [];
$values = ' ' . $values;
foreach ($columns->select as $title => $field) {
if (is_string($title)) {
$names[] = $schema->quoteColumnName($title);
} elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/' , $field, $matches)) {
$names[] = $schema->quoteColumnName($matches[2]);
} else {
$names[] = $schema->quoteColumnName($field);
}
}
return [$names, $values, $params];
}
Defined in:
yii\
Prepares a VALUES part for an INSERT SQL statement.
| protected array prepareInsertValues ( string $table, array|yii\ | ||
| $table | string |
The table that new rows will be inserted into. |
| $columns | array|yii\ |
The column data (name => value) to be inserted into the table or instance of Query to perform INSERT INTO ... SELECT SQL statement. |
| $params | array |
The binding parameters that will be generated by this method. They should be bound to the DB command later. |
| return | array |
Array of column names, placeholders, values and params. |
|---|---|---|
protected function prepareInsertValues($table, $columns, $params = [])
{
$schema = $this->db->getSchema();
$tableSchema = $schema->getTableSchema($table);
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
$names = [];
$placeholders = [];
$values = ' DEFAULT VALUES';
if ($columns instanceof Query) {
list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
} else {
foreach ($columns as $name => $value) {
$names[] = $schema->quoteColumnName($name);
$value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
if ($value instanceof ExpressionInterface) {
$placeholders[] = $this->buildExpression($value, $params);
} elseif ($value instanceof \yii\db\Query) {
list($sql, $params) = $this->build($value, $params);
$placeholders[] = "($sql)";
} else {
$placeholders[] = $this->bindParam($value, $params);
}
}
}
return [$names, $placeholders, $values, $params];
}
Performs driver-specific preparation after yii\
SQL Server rejects FETCH NEXT 0 and wrapping a compound query requires every result column to have a unique
name. Applying TOP (0) to every UNION operand preserves zero-row semantics without a derived table.
Implementations must not modify the given query; they must return a modified clone instead.
| protected yii\ | ||
| $query | yii\ |
The prepared query. |
| return | yii\ |
The query to build. |
|---|---|---|
protected function prepareSelectQuery(Query $query): Query
{
if ($query->union === null || $query->union === [] || !$this->isZeroLimit($query->unionLimit)) {
return $query;
}
$query = clone $query;
$query->limit = 0;
$query->offset = null;
$query->unionOrderBy = null;
$query->unionLimit = null;
$query->unionOffset = null;
foreach ($query->union as $index => $union) {
if ($union['query'] instanceof Query) {
$unionQuery = clone $union['query'];
if ($unionQuery->union === null || $unionQuery->union === []) {
$unionQuery->limit = 0;
$unionQuery->offset = null;
} else {
$unionQuery->unionLimit = 0;
}
$union['query'] = $unionQuery;
} else {
$union['query'] = $this->addTopZero($union['query']);
}
$query->union[$index] = $union;
}
return $query;
}
Defined in:
yii\
Prepares a SET parts for an UPDATE SQL statement.
| protected array prepareUpdateSets ( string $table, array $columns, array $params = [] ) | ||
| $table | string |
The table to be updated. |
| $columns | array |
The column data (name => value) to be updated. |
| $params | array |
The binding parameters that will be modified by this method so that they can be bound to the DB command later. |
| return | array |
An array |
|---|---|---|
protected function prepareUpdateSets($table, $columns, $params = [])
{
$tableSchema = $this->db->getTableSchema($table);
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
$sets = [];
foreach ($columns as $name => $value) {
$value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
if ($value instanceof ExpressionInterface) {
$placeholder = $this->buildExpression($value, $params);
} else {
$placeholder = $this->bindParam($value, $params);
}
$sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
}
return [$sets, $params];
}
Defined in:
yii\
| protected array prepareUpsertColumns ( string $table, array|yii\ | ||
| $table | string | |
| $insertColumns | array|yii\ |
|
| $updateColumns | array|boolean | |
| $constraints | yii\ |
This parameter recieves a matched constraint list. The constraints will be unique by their column names. |
protected function prepareUpsertColumns($table, $insertColumns, $updateColumns, &$constraints = [])
{
if ($insertColumns instanceof Query) {
list($insertNames) = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
} else {
$insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
}
$uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
$uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
if ($updateColumns !== true) {
return [$uniqueNames, $insertNames, null];
}
return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
}
Defined in:
yii\
Prepares the SET assignments for the update branch of an upsert statement.
| protected array{string[], array | ||
| $table | string |
The table that the upsert targets. |
| $updateColumns | array |
|
| $updateNames | string[]|null |
Quoted column names eligible for update. |
| $params | array |
The binding parameters modified by this method. |
| $sourceColumnRef | callable |
Maps a quoted column name to its source reference. |
| return | array{string[], array |
The |
|---|---|---|
protected function prepareUpsertSets(
string $table,
array|bool $updateColumns,
array|null $updateNames,
array $params,
Closure $sourceColumnRef,
): array {
if ($updateColumns === true && $updateNames !== null) {
$updateColumns = [];
foreach ($updateNames as $quotedName) {
$updateColumns[$quotedName] = new Expression($sourceColumnRef($quotedName));
}
}
return $this->prepareUpdateSets($table, $updateColumns, $params);
}
Builds a SQL statement for renaming a column.
| public string renameColumn ( string $table, string $oldName, string $newName ) | ||
| $table | string |
The table whose column is to be renamed. The name will be properly quoted by the method. |
| $oldName | string |
The old name of the column. The name will be properly quoted by the method. |
| $newName | string |
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. |
|---|---|---|
public function renameColumn($table, $oldName, $newName)
{
$schema = $this->db->getSchema();
$table = Quoter::escapeLiteralValue($this->db->quoteTableName($table));
$oldName = Quoter::escapeLiteralValue($this->db->quoteColumnName($oldName));
$newName = $this->db->quoteSql($this->db->quoteColumnName($newName));
$newName = Quoter::extractSimpleIdentifier($newName);
$newName = Quoter::escapeLiteralValue($schema->unquoteSimpleColumnName($newName));
return <<<SQL
EXEC sp_rename @objname = N'{$table}.{$oldName}', @newname = N'{$newName}', @objtype = N'COLUMN'
SQL;
}
Builds a SQL statement for renaming a DB table.
| public string renameTable ( string $oldName, string $newName ) | ||
| $oldName | string |
The table to be renamed. The name will be properly quoted by the method. |
| $newName | string |
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($oldName, $newName)
{
$schema = $this->db->getSchema();
$oldTableName = Quoter::escapeLiteralValue($this->db->quoteTableName($oldName));
$newTableName = $this->db->quoteSql($this->db->quoteTableName($newName));
$newTableName = Quoter::extractSimpleIdentifier($newTableName);
$newTableName = Quoter::escapeLiteralValue($schema->unquoteSimpleTableName($newTableName));
return <<<SQL
EXEC sp_rename @objname = N'{$oldTableName}', @newname = N'{$newTableName}', @objtype = N'OBJECT'
SQL;
}
Creates a SQL statement for resetting 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 the next value after the current maximum identity value.
See also:
- https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql
- https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-identity-columns-transact-sql
- https://learn.microsoft.com/en-us/sql/t-sql/functions/ident-seed-transact-sql
- https://learn.microsoft.com/en-us/sql/t-sql/functions/ident-incr-transact-sql
| public string resetSequence ( string $tableName, integer|null $value = null ) | ||
| $tableName | string |
The name of the table whose primary key sequence will be reset. |
| $value | integer|null |
The integer 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 the next value after the current maximum identity value. |
| return | string |
The SQL statement for resetting sequence. |
|---|---|---|
| throws | yii\ |
if the table does not exist or there is no sequence associated with the table. |
public function resetSequence($tableName, $value = null)
{
$table = $this->db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) {
$quotedTableName = $this->db->quoteTableName($tableName);
$tableNameLiteral = Quoter::escapeLiteralValue($quotedTableName);
$requestedNextValue = $value === null ? 'NULL' : (string) (int) $value;
/** @var Schema $dbSchema */
$dbSchema = $this->db->getSchema();
$systemCatalogName = $dbSchema->quoteSystemCatalogName(
$table instanceof TableSchema ? $table->catalogName : null,
);
return <<<SQL
DECLARE @tableName NVARCHAR(MAX) = N'{$tableNameLiteral}'
DECLARE @requestedNextValue DECIMAL(38, 0) = {$requestedNextValue}
DECLARE @identityColumn SYSNAME
DECLARE @seedValue DECIMAL(38, 0)
DECLARE @incrementValue DECIMAL(38, 0)
DECLARE @lastValue DECIMAL(38, 0)
DECLARE @maxValue DECIMAL(38, 0)
DECLARE @reseedValue DECIMAL(38, 0)
DECLARE @maxSql NVARCHAR(MAX)
DECLARE @checkIdentSql NVARCHAR(MAX)
SELECT
@identityColumn = [name],
@seedValue = CONVERT(DECIMAL(38, 0), [seed_value]),
@incrementValue = CONVERT(DECIMAL(38, 0), [increment_value]),
@lastValue = CONVERT(DECIMAL(38, 0), [last_value])
FROM {$systemCatalogName}.[identity_columns]
WHERE [object_id] = OBJECT_ID(@tableName, N'U')
IF @identityColumn IS NULL
BEGIN
THROW 50000, 'Identity column not found on table.', 1;
END
SET @maxSql = N'SELECT @maxValue = CONVERT(DECIMAL(38, 0), MAX('
+ QUOTENAME(@identityColumn)
+ N')) FROM '
+ @tableName
EXEC sp_executesql
@maxSql,
N'@maxValue DECIMAL(38, 0) OUTPUT',
@maxValue OUTPUT
SET @reseedValue = CASE
WHEN @requestedNextValue IS NOT NULL AND (@maxValue IS NOT NULL OR @lastValue IS NOT NULL)
THEN @requestedNextValue - @incrementValue
WHEN @requestedNextValue IS NOT NULL
THEN @requestedNextValue
WHEN @maxValue IS NOT NULL
THEN @maxValue
WHEN @lastValue IS NOT NULL
THEN @seedValue - @incrementValue
ELSE @seedValue
END
SET @checkIdentSql = N'DBCC CHECKIDENT (N'''
+ REPLACE(@tableName, '''', '''''')
+ N''', RESEED, '
+ CONVERT(NVARCHAR(50), @reseedValue)
+ N')'
EXEC (@checkIdentSql)
SQL;
} elseif ($table === null) {
throw new InvalidArgumentException("Table not found: $tableName");
}
throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
}
Creates a SELECT EXISTS() SQL statement.
| public string selectExists ( mixed $rawSql ) | ||
| $rawSql | mixed |
The subquery in a raw form to select from. |
| return | string |
The SELECT EXISTS() SQL statement. |
|---|---|---|
public function selectExists($rawSql)
{
return <<<SQL
SELECT CASE WHEN EXISTS($rawSql) THEN 1 ELSE 0 END AS [result]
SQL;
}
Defined in:
yii\
Setter for $conditionClasses property.
See also $conditionClasses.
| public mixed setConditionClasses ( string[] $classes ) | ||
| $classes | string[] |
Map of condition aliases to condition classes. For example:
|
public function setConditionClasses($classes)
{
$this->conditionClasses = array_merge($this->conditionClasses, $classes);
}
Defined in:
yii\
Setter for $expressionBuilders property.
See also $expressionBuilders.
| public mixed setExpressionBuilders ( string[] $builders ) | ||
| $builders | string[] |
Array of builders that should be merged with the pre-defined ones in $expressionBuilders property. |
public function setExpressionBuilders($builders)
{
$this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
}
Defined in:
yii\
Builds a SQL statement for truncating a DB table.
| public string truncateTable ( string $table ) | ||
| $table | string |
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)
{
return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
}
Creates an UPDATE SQL statement.
Excludes server-managed rowversion columns from the SET clause and renders any rowversion in the WHERE as a
binary literal, enabling a rowversion column to serve as the optimistic lock attribute.
Note: SQL Server regenerates the rowversion on every write and the in-memory attribute is not refreshed
afterwards; reload the record before saving the same instance again to avoid a spurious StaleObjectException.
For example,
$params = [];
$sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
The method will properly escape the table and column names.
| public string update ( mixed $table, mixed $columns, mixed $condition, mixed &$params ) | ||
| $table | mixed |
The table to be updated. |
| $columns | mixed |
The column data (name => value) to be updated. |
| $condition | mixed |
The condition that will be put in the WHERE part. Please
refer to yii\ |
| $params | mixed |
The binding parameters that will be modified by this method so that they can be bound to the DB command later. |
| return | string |
The UPDATE SQL |
|---|---|---|
public function update($table, $columns, $condition, &$params)
{
$schema = $this->db->getTableSchema($table);
if ($schema !== null) {
foreach ($columns as $name => $_value) {
$column = $schema->columns[$name] ?? null;
if ($column instanceof ColumnSchema && $column->isRowVersion()) {
unset($columns[$name]); // server-managed; never in the SET clause.
}
}
$condition = $this->castRowVersionConditions($schema, $condition);
}
return parent::update($table, $columns, $condition, $params);
}
Generates a MERGE statement that inserts a row or updates the matching one in a single atomic operation.
The WITH (HOLDLOCK) table hint serializes concurrent upserts so they cannot insert duplicate keys.
See also:
| public mixed upsert ( mixed $table, mixed $insertColumns, mixed $updateColumns, mixed &$params ) | ||
| $table | mixed | |
| $insertColumns | mixed | |
| $updateColumns | mixed | |
| $params | mixed | |
public function upsert($table, $insertColumns, $updateColumns, &$params)
{
[$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
$table,
$insertColumns,
$updateColumns,
$constraints,
);
if ($uniqueNames === []) {
return $this->insert($table, $insertColumns, $params);
}
$onCondition = ['or'];
$quotedTableName = $this->db->quoteTableName($table);
foreach ($constraints as $constraint) {
$constraintCondition = ['and'];
foreach ($constraint->columnNames as $name) {
$quotedName = $this->db->quoteColumnName($name);
$constraintCondition[] = "{$quotedTableName}.{$quotedName}=[EXCLUDED].{$quotedName}";
}
$onCondition[] = $constraintCondition;
}
$on = $this->buildCondition($onCondition, $params);
[, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
$source = $placeholders !== []
? 'VALUES (' . implode(', ', $placeholders) . ')'
: ltrim($values, ' ');
$columnList = implode(', ', $insertNames);
$insertValues = [];
foreach ($insertNames as $quotedName) {
$insertValues[] = "[EXCLUDED].{$quotedName}";
}
$insertColumnRefs = implode(', ', $insertValues);
$mergeSql = <<<SQL
MERGE {$quotedTableName} WITH (HOLDLOCK) USING ({$source}) AS [EXCLUDED] ({$columnList}) ON ({$on})
SQL;
$insertSql = "INSERT ({$columnList}) VALUES ({$insertColumnRefs})";
if ($updateColumns === false || $updateNames === []) {
return "{$mergeSql} WHEN NOT MATCHED THEN {$insertSql};";
}
[$updates, $params] = $this->prepareUpsertSets(
$table,
$updateColumns,
$updateNames,
$params,
static fn($quotedName): string => "[EXCLUDED].{$quotedName}",
);
$updateSql = 'UPDATE SET ' . implode(', ', $updates);
return "{$mergeSql} WHEN MATCHED THEN {$updateSql} WHEN NOT MATCHED THEN {$insertSql};";
}
User Contributed Notes
Leave a comment
Join the conversation to share a note.