0 follower

Class yii\db\mssql\QueryBuilder

Inheritanceyii\db\mssql\QueryBuilder » yii\db\QueryBuilder » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.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 2008 and above).

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$db yii\db\Connection The database connection. yii\db\QueryBuilder
$separator string The separator between different fragments of a SQL statement. yii\db\QueryBuilder
$typeMap array Mapping from abstract column types (keys) to physical column types (values). yii\db\mssql\QueryBuilder

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$conditionBuilders array Map of query condition to builder methods. yii\db\QueryBuilder
$conditionClasses array Map of condition aliases to condition classes. yii\db\QueryBuilder
$expressionBuilders string[]|yii\db\ExpressionBuilderInterface[] Maps expression class to expression builder class. yii\db\QueryBuilder

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
addCheck() Creates a SQL command for adding a check constraint to an existing table. yii\db\QueryBuilder
addColumn() Builds a SQL statement for adding a new DB column. yii\db\QueryBuilder
addCommentOnColumn() Builds a SQL command for adding comment to column. yii\db\mssql\QueryBuilder
addCommentOnTable() Builds a SQL command for adding comment to table. yii\db\mssql\QueryBuilder
addDefaultValue() Creates a SQL command for adding a default value constraint to an existing table. yii\db\mssql\QueryBuilder
addForeignKey() Builds a SQL statement for adding a foreign key constraint to an existing table. yii\db\QueryBuilder
addPrimaryKey() Builds a SQL statement for adding a primary key constraint to an existing table. yii\db\QueryBuilder
addUnique() Creates a SQL command for adding an unique constraint to an existing table. yii\db\QueryBuilder
alterColumn() Builds a SQL statement for changing the definition of a column. yii\db\mssql\QueryBuilder
batchInsert() Generates a batch INSERT SQL statement. yii\db\QueryBuilder
bindParam() Helper method to add $value to $params array using PARAM_PREFIX. yii\db\QueryBuilder
build() Generates a SELECT SQL statement from a yii\db\Query object. yii\db\QueryBuilder
buildAndCondition() Connects two or more SQL expressions with the AND or OR operator. yii\db\QueryBuilder
buildBetweenCondition() Creates an SQL expressions with the BETWEEN operator. yii\db\QueryBuilder
buildColumns() Processes columns and properly quotes them if necessary. yii\db\QueryBuilder
buildCondition() Parses the condition specification and generates the corresponding SQL expression. yii\db\QueryBuilder
buildExistsCondition() Creates an SQL expressions with the EXISTS operator. yii\db\QueryBuilder
buildExpression() Builds given $expression yii\db\QueryBuilder
buildFrom() yii\db\QueryBuilder
buildGroupBy() yii\db\QueryBuilder
buildHashCondition() Creates a condition based on column-value pairs. yii\db\QueryBuilder
buildHaving() yii\db\QueryBuilder
buildInCondition() Creates an SQL expressions with the IN operator. yii\db\QueryBuilder
buildJoin() yii\db\QueryBuilder
buildLikeCondition() Creates an SQL expressions with the LIKE operator. yii\db\QueryBuilder
buildLimit() yii\db\QueryBuilder
buildNotCondition() Inverts an SQL expressions with NOT operator. yii\db\QueryBuilder
buildOrderBy() yii\db\QueryBuilder
buildOrderByAndLimit() Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL. yii\db\mssql\QueryBuilder
buildSelect() yii\db\QueryBuilder
buildSimpleCondition() Creates an SQL expressions like "column" operator value. yii\db\QueryBuilder
buildUnion() yii\db\QueryBuilder
buildWhere() yii\db\QueryBuilder
buildWithQueries() yii\db\QueryBuilder
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
checkIntegrity() Builds a SQL statement for enabling or disabling integrity check. yii\db\mssql\QueryBuilder
className() Returns the fully qualified name of this class. yii\base\BaseObject
createConditionFromArray() Transforms $condition defined in array format (as described in yii\db\Query::where() to instance of yii\db\condition\ConditionInterface according to $conditionClasses map. yii\db\QueryBuilder
createIndex() Builds a SQL statement for creating a new index. yii\db\QueryBuilder
createTable() Builds a SQL statement for creating a new DB table. yii\db\QueryBuilder
createView() Creates a SQL View. yii\db\QueryBuilder
delete() Creates a DELETE SQL statement. yii\db\QueryBuilder
dropCheck() Creates a SQL command for dropping a check constraint. yii\db\QueryBuilder
dropColumn() Drop all constraints before column delete {@inheritdoc} yii\db\mssql\QueryBuilder
dropCommentFromColumn() Builds a SQL command for adding comment to column. yii\db\mssql\QueryBuilder
dropCommentFromTable() Builds a SQL command for adding comment to table. yii\db\mssql\QueryBuilder
dropDefaultValue() Creates a SQL command for dropping a default value constraint. yii\db\mssql\QueryBuilder
dropForeignKey() Builds a SQL statement for dropping a foreign key constraint. yii\db\QueryBuilder
dropIndex() Builds a SQL statement for dropping an index. yii\db\QueryBuilder
dropPrimaryKey() Builds a SQL statement for removing a primary key constraint to an existing table. yii\db\QueryBuilder
dropTable() Builds a SQL statement for dropping a DB table. yii\db\QueryBuilder
dropUnique() Creates a SQL command for dropping an unique constraint. yii\db\QueryBuilder
dropView() Drops a SQL View. yii\db\QueryBuilder
executeResetSequence() Execute a SQL statement for resetting the sequence value of a table's primary key. yii\db\QueryBuilder
getColumnType() Converts an abstract column type into a physical column type. yii\db\mssql\QueryBuilder
getExpressionBuilder() Gets object of yii\db\ExpressionBuilderInterface that is suitable for $expression. yii\db\QueryBuilder
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
insert() {@inheritdoc} Added OUTPUT construction for getting inserted data (for SQL Server 2005 or later) OUTPUT clause - The OUTPUT clause is new to SQL Server 2005 and has the ability to access the INSERTED and DELETED tables as is the case with a trigger. yii\db\mssql\QueryBuilder
renameColumn() Builds a SQL statement for renaming a column. yii\db\mssql\QueryBuilder
renameTable() Builds a SQL statement for renaming a DB table. yii\db\mssql\QueryBuilder
resetSequence() Creates a SQL statement for resetting the sequence value of a table's primary key. yii\db\mssql\QueryBuilder
selectExists() Creates a SELECT EXISTS() SQL statement. yii\db\mssql\QueryBuilder
setConditionClasses() Setter for $conditionClasses property. yii\db\QueryBuilder
setExpressionBuilders() Setter for $expressionBuilders property. yii\db\QueryBuilder
truncateTable() Builds a SQL statement for truncating a DB table. yii\db\QueryBuilder
update() Creates an UPDATE SQL statement. yii\db\mssql\QueryBuilder
upsert() Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do. yii\db\mssql\QueryBuilder

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
buildAddCommentSql() Builds a SQL command for adding or updating a comment to a table or a column. The command built will check if a comment already exists. If so, it will be updated, otherwise, it will be added. yii\db\mssql\QueryBuilder
buildRemoveCommentSql() Builds a SQL command for removing a comment from a table or a column. The command built will check if a comment already exists before trying to perform the removal. yii\db\mssql\QueryBuilder
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\db\QueryBuilder
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\db\mssql\QueryBuilder
extractAlias() Extracts table alias if there is one or returns false yii\db\mssql\QueryBuilder
getAllColumnNames() Returns an array of column names given model name. yii\db\mssql\QueryBuilder
hasLimit() Checks to see if the given limit is effective. yii\db\QueryBuilder
hasOffset() Checks to see if the given offset is effective. yii\db\QueryBuilder
isOldMssql() yii\db\mssql\QueryBuilder
newBuildOrderByAndLimit() Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2012 or newer. yii\db\mssql\QueryBuilder
oldBuildOrderByAndLimit() Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2005 to 2008. yii\db\mssql\QueryBuilder
prepareInsertSelectSubQuery() Prepare select-subquery and field names for INSERT INTO . yii\db\QueryBuilder
prepareInsertValues() Prepares a VALUES part for an INSERT SQL statement. yii\db\QueryBuilder
prepareUpdateSets() Prepares a SET parts for an UPDATE SQL statement. yii\db\QueryBuilder
prepareUpsertColumns() yii\db\QueryBuilder

Constants

Hide inherited constants

ConstantValueDescriptionDefined By
PARAM_PREFIX ':qp' The prefix for automatically generated query binding parameters. yii\db\QueryBuilder

Property Details

$typeMap public property

Mapping from abstract column types (keys) to physical column types (values).

public array $typeMap = [\yii\db\mssql\Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY', \yii\db\mssql\Schema::TYPE_UPK => 'int IDENTITY PRIMARY KEY', \yii\db\mssql\Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY', \yii\db\mssql\Schema::TYPE_UBIGPK => 'bigint IDENTITY PRIMARY KEY', \yii\db\mssql\Schema::TYPE_CHAR => 'nchar(1)', \yii\db\mssql\Schema::TYPE_STRING => 'nvarchar(255)', \yii\db\mssql\Schema::TYPE_TEXT => 'nvarchar(max)', \yii\db\mssql\Schema::TYPE_TINYINT => 'tinyint', \yii\db\mssql\Schema::TYPE_SMALLINT => 'smallint', \yii\db\mssql\Schema::TYPE_INTEGER => 'int', \yii\db\mssql\Schema::TYPE_BIGINT => 'bigint', \yii\db\mssql\Schema::TYPE_FLOAT => 'float', \yii\db\mssql\Schema::TYPE_DOUBLE => 'float', \yii\db\mssql\Schema::TYPE_DECIMAL => 'decimal(18,0)', \yii\db\mssql\Schema::TYPE_DATETIME => 'datetime', \yii\db\mssql\Schema::TYPE_TIMESTAMP => 'datetime', \yii\db\mssql\Schema::TYPE_TIME => 'time', \yii\db\mssql\Schema::TYPE_DATE => 'date', \yii\db\mssql\Schema::TYPE_BINARY => 'varbinary(max)', \yii\db\mssql\Schema::TYPE_BOOLEAN => 'bit', \yii\db\mssql\Schema::TYPE_MONEY => 'decimal(19,4)']

Method Details

addCommentOnColumn() public method (available since version 2.0.8)

Builds a SQL command for adding comment to column.

public string addCommentOnColumn ( $table, $column, $comment )
$table string

The table whose column is to be commented. The table name will be properly quoted by the method.

$column string

The name of the column to be commented. The column name will be properly quoted by the method.

$comment string

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

addCommentOnTable() public method (available since version 2.0.8)

Builds a SQL command for adding comment to table.

public string addCommentOnTable ( $table, $comment )
$table string

The table whose column is to be commented. The table name will be properly quoted by the method.

$comment string

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

addDefaultValue() public method (available since version 2.0.13)

Creates a SQL command for adding a default value constraint to an existing table.

public string addDefaultValue ( $name, $table, $column, $value )
$name string

The name of the default value constraint. The name will be properly quoted by the method.

$table string

The table that the default value constraint will be added to. The name will be properly quoted by the method.

$column string

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\base\NotSupportedException

if this is not supported by the underlying DBMS.

alterColumn() public method

Builds a SQL statement for changing the definition of a column.

public string alterColumn ( $table, $column, $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 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.

throws yii\base\NotSupportedException

if this is not supported by the underlying DBMS.

buildAddCommentSql() protected method (available since version 2.0.24)

Builds a SQL command for adding or updating a comment to a table or a column. The command built will check if a comment already exists. If so, it will be updated, otherwise, it will be added.

protected string buildAddCommentSql ( $comment, $table, $column null )
$comment string

The text of the comment to be added. The comment will be properly quoted by the method.

$table string

The table to be commented or whose column is to be commented. The table name will be properly quoted by the method.

$column string

Optional. The name of the column to be commented. If empty, the command will add the comment to the table instead. The column name will be properly quoted by the method.

return string

The SQL statement for adding a comment.

throws yii\base\InvalidArgumentException

if the table does not exist.

buildOrderByAndLimit() public method

Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.

public string buildOrderByAndLimit ( $sql, $orderBy, $limit, $offset )
$sql string

The existing SQL (without ORDER BY/LIMIT/OFFSET)

$orderBy array

The order by columns. See yii\db\Query::orderBy() for more details on how to specify this parameter.

$limit integer

The limit number. See yii\db\Query::limit() for more details.

$offset integer

The offset number. See yii\db\Query::offset() for more details.

return string

The SQL completed with ORDER BY/LIMIT/OFFSET (if any)

buildRemoveCommentSql() protected method (available since version 2.0.24)

Builds a SQL command for removing a comment from a table or a column. The command built will check if a comment already exists before trying to perform the removal.

protected string buildRemoveCommentSql ( $table, $column null )
$table string

The table that will have the comment removed or whose column will have the comment removed. The table name will be properly quoted by the method.

$column string

Optional. The name of the column whose comment will be removed. If empty, the command will remove the comment from the table instead. The column name will be properly quoted by the method.

return string

The SQL statement for removing the comment.

throws yii\base\InvalidArgumentException

if the table does not exist.

checkIntegrity() public method

Builds a SQL statement for enabling or disabling integrity check.

public string checkIntegrity ( $check true, $schema '', $table '' )
$check boolean

Whether to turn on or off the integrity check.

$schema string

The schema of the tables.

$table string

The table name.

return string

The SQL statement for checking integrity

defaultExpressionBuilders() protected method (available since version 2.0.14)

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 ( )
dropColumn() public method

Drop all constraints before column delete {@inheritdoc}

public void dropColumn ( $table, $column )
$table
$column
dropCommentFromColumn() public method (available since version 2.0.8)

Builds a SQL command for adding comment to column.

public string dropCommentFromColumn ( $table, $column )
$table string

The table whose column is to be commented. The table name will be properly quoted by the method.

$column string

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

dropCommentFromTable() public method (available since version 2.0.8)

Builds a SQL command for adding comment to table.

public string dropCommentFromTable ( $table )
$table string

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

dropDefaultValue() public method (available since version 2.0.13)

Creates a SQL command for dropping a default value constraint.

public string dropDefaultValue ( $name, $table )
$name string

The name of the default value constraint to be dropped. The name will be properly quoted by the method.

$table string

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\base\NotSupportedException

if this is not supported by the underlying DBMS.

extractAlias() protected method (available since version 2.0.24)

Extracts table alias if there is one or returns false

protected boolean|array extractAlias ( $table )
$table
getAllColumnNames() protected method

Returns an array of column names given model name.

protected array|null getAllColumnNames ( $modelClass null )
$modelClass string

Name of the model class

return array|null

Array of column names

getColumnType() public method

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 ( $type )
$type string|yii\db\ColumnSchemaBuilder

Abstract column type

return string

Physical column type.

insert() public method

{@inheritdoc} Added OUTPUT construction for getting inserted data (for SQL Server 2005 or later) OUTPUT clause - The OUTPUT clause is new to SQL Server 2005 and has the ability to access the INSERTED and DELETED tables as is the case with a trigger.

public void insert ( $table, $columns, &$params )
$table
$columns
$params
isOldMssql() protected method
Deprecated since version 2.0.14: Use yii\db\mssql\Schema::getServerVersion() with \version_compare().

protected boolean isOldMssql ( )
return boolean

Whether the version of the MSSQL being used is older than 2012.

throws yii\base\InvalidConfigException
throws yii\db\Exception
newBuildOrderByAndLimit() protected method

Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2012 or newer.

protected string newBuildOrderByAndLimit ( $sql, $orderBy, $limit, $offset )
$sql string

The existing SQL (without ORDER BY/LIMIT/OFFSET)

$orderBy array

The order by columns. See yii\db\Query::orderBy() for more details on how to specify this parameter.

$limit integer

The limit number. See yii\db\Query::limit() for more details.

$offset integer

The offset number. See yii\db\Query::offset() for more details.

return string

The SQL completed with ORDER BY/LIMIT/OFFSET (if any)

oldBuildOrderByAndLimit() protected method

Builds the ORDER BY/LIMIT/OFFSET clauses for SQL SERVER 2005 to 2008.

protected string oldBuildOrderByAndLimit ( $sql, $orderBy, $limit, $offset )
$sql string

The existing SQL (without ORDER BY/LIMIT/OFFSET)

$orderBy array

The order by columns. See yii\db\Query::orderBy() for more details on how to specify this parameter.

$limit integer

The limit number. See yii\db\Query::limit() for more details.

$offset integer

The offset number. See yii\db\Query::offset() for more details.

return string

The SQL completed with ORDER BY/LIMIT/OFFSET (if any)

renameColumn() public method

Builds a SQL statement for renaming a column.

public string renameColumn ( $table, $oldName, $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.

renameTable() public method

Builds a SQL statement for renaming a DB table.

public string renameTable ( $oldName, $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.

resetSequence() public method

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 1.

public string resetSequence ( $tableName, $value null )
$tableName string

The name of the table whose primary key sequence will be reset

$value mixed

The value for the primary key of the next new row inserted. If this is not set, the next new row's primary key will have a value 1.

return string

The SQL statement for resetting sequence

throws yii\base\InvalidArgumentException

if the table does not exist or there is no sequence associated with the table.

selectExists() public method (available since version 2.0.8)

Creates a SELECT EXISTS() SQL statement.

public string selectExists ( $rawSql )
$rawSql string

The subquery in a raw form to select from.

return string

The SELECT EXISTS() SQL statement.

update() public method

Creates an UPDATE SQL statement.

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 ( $table, $columns, $condition, &$params )
$table string

The table to be updated.

$columns array

The column data (name => value) to be updated.

$condition array|string

The condition that will be put in the WHERE part. Please refer to yii\db\Query::where() on how to specify condition.

$params array

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

upsert() public method (available since version 2.0.14)

Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique constraints), or update them if they do.

For example,

$sql = $queryBuilder->upsert('pages', [
    'name' => 'Front page',
    'url' => 'http://example.com/', // url is unique
    'visits' => 0,
], [
    'visits' => new \yii\db\Expression('visits + 1'),
], $params);

The method will properly escape the table and column names.

See also:

public string upsert ( $table, $insertColumns, $updateColumns, &$params )
$table string

The table that new rows will be inserted into/updated in.

$insertColumns array|yii\db\Query

The column data (name => value) to be inserted into the table or instance of yii\db\Query to perform INSERT INTO ... SELECT SQL statement.

$updateColumns array|boolean

The column data (name => value) to be updated if they already exist. If true is passed, the column data will be updated to match the insert column data. If false is passed, no update will be performed if the column data already exists.

$params array

The binding parameters that will be generated by this method. They should be bound to the DB command later.

return string

The resulting SQL.

throws yii\base\NotSupportedException

if this is not supported by the underlying DBMS.