Class yii\db\mssql\Schema
| Inheritance | yii\ |
|---|---|
| Implements | yii\ |
| Uses Traits | yii\ |
| Available since version | 2.0 |
| Source Code | https://github.com/yiisoft/yii2/blob/master/framework/db/mssql/Schema.php |
Schema is the class for retrieving metadata from MS SQL Server databases (version 2019 and above).
Public Properties
| Property | Type | Description | Defined By |
|---|---|---|---|
| $columnSchemaClass | class-string<\yii\db\T>|array{class?: class-string<\yii\db\T>, __class?: class-string<\yii\db\T>} | Column schema class or class config | yii\ |
| $db | yii\ |
The database connection | yii\ |
| $defaultSchema | string | The default schema used for the current session. | yii\ |
| $exceptionMap | array | Map of DB errors and corresponding exceptions If left part is found in DB error message exception class from the right part is used. | yii\ |
| $lastInsertID | string | The row ID of the last row inserted, or the last value retrieved from the sequence object. | yii\ |
| $queryBuilder | \ |
The query builder for this connection. | yii\ |
| $schemaChecks | \ |
Check constraints for all tables in the database. | yii\ |
| $schemaDefaultValues | yii\ |
Default value constraints for all tables in the database. | yii\ |
| $schemaForeignKeys | \ |
Foreign keys for all tables in the database. | yii\ |
| $schemaIndexes | \ |
Indexes for all tables in the database. | yii\ |
| $schemaNames | string[] | All schema names in the database, except system schemas. | yii\ |
| $schemaPrimaryKeys | yii\ |
Primary keys for all tables in the database. | yii\ |
| $schemaUniques | \ |
Unique constraints for all tables in the database. | yii\ |
| $serverVersion | string | Server version as a string. | yii\ |
| $systemSchemaNames | array | yii\ |
|
| $tableNames | string[] | All table names in the database. | yii\ |
| $tableSchemas | yii\ |
The metadata for all tables in the database. | yii\ |
| $transactionIsolationLevel | string | The transaction isolation level to use for this transaction. | yii\ |
| $typeMap | array | Mapping from physical column types (keys) to abstract column types (values). | yii\ |
| $viewNames | string[] | All view names in the database. | yii\ |
Protected Properties
| Property | Type | Description | Defined By |
|---|---|---|---|
| $columnQuoteCharacter | string|string[] | Character used to quote column names. | yii\ |
| $tableQuoteCharacter | string|string[] | Character used to quote schema, table, etc. | 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\ |
| canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
| canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
| className() | Returns the fully qualified name of this class. | yii\ |
| convertException() | Converts a DB exception to a more concrete one if possible. | yii\ |
| createColumnSchemaBuilder() | Create a column schema builder instance giving the type and value precision. | yii\ |
| createQueryBuilder() | Creates a query builder for the MSSQL database. | yii\ |
| createSavepoint() | Creates a new savepoint. | yii\ |
| findUniqueIndexes() | Returns all unique indexes for the given table. | yii\ |
| getLastInsertID() | Returns the ID of the last inserted row or sequence value. | yii\ |
| getPdoType() | Determines the PDO type for the given PHP data value. | yii\ |
| getQueryBuilder() | yii\ |
|
| getRawTableName() | Returns the actual name of a given table name. | yii\ |
| getSchemaChecks() | Returns check constraints for all tables in the database. | yii\ |
| getSchemaDefaultValues() | Returns default value constraints for all tables in the database. | yii\ |
| getSchemaForeignKeys() | Returns foreign keys for all tables in the database. | yii\ |
| getSchemaIndexes() | Returns indexes for all tables in the database. | yii\ |
| getSchemaNames() | Returns all schema names in the database, except system schemas. | yii\ |
| getSchemaPrimaryKeys() | Returns primary keys for all tables in the database. | yii\ |
| getSchemaUniques() | Returns unique constraints for all tables in the database. | yii\ |
| getServerVersion() | Returns a server version as a string comparable by \ |
yii\ |
| getTableChecks() | Obtains the check constraints information for the named table. | yii\ |
| getTableDefaultValues() | Obtains the default value constraints information for the named table. | yii\ |
| getTableForeignKeys() | Obtains the foreign keys information for the named table. | yii\ |
| getTableIndexes() | Obtains the indexes information for the named table. | yii\ |
| getTableNames() | Returns all table names in the database. | yii\ |
| getTablePrimaryKey() | Obtains the primary key for the named table. | yii\ |
| getTableSchema() | Obtains the metadata for the named table. | yii\ |
| getTableSchemas() | Returns the metadata for all tables in the database. | yii\ |
| getTableUniques() | Obtains the unique constraints information for the named table. | yii\ |
| getViewNames() | Returns all view names in the database. | 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() | Executes the INSERT command, returning primary key values. | yii\ |
| isReadQuery() | Returns a value indicating whether a SQL statement is for read purpose. | yii\ |
| quoteColumnName() | Quotes a column name for use in a query. | yii\ |
| quoteSimpleColumnName() | Quotes a simple column name for use in a query. | yii\ |
| quoteSimpleTableName() | Quotes a simple table name for use in a query. | yii\ |
| quoteSystemCatalogName() | Quotes the [sys] system catalog name, optionally qualified by the database catalog. |
yii\ |
| quoteTableName() | Qualifies single-part table names with {@see $defaultSchema} when it differs from 'dbo', ensuring
unqualified DDL and DML statements target the configured schema rather than the SQL Server login default. |
yii\ |
| quoteValue() | Quotes a string value for use in a query. | yii\ |
| refresh() | Refreshes the schema. | yii\ |
| refreshTableSchema() | Refreshes the particular table schema. | yii\ |
| releaseSavepoint() | Releases an existing savepoint. | yii\ |
| resolveRawCatalogSchemaName() | Resolves a schema argument into optional catalog and schema names without loading database metadata. | yii\ |
| resolveRawTableName() | Resolves the table name and schema name (if any) without loading database metadata. | yii\ |
| rollBackSavepoint() | Rolls back to a previously created savepoint. | yii\ |
| setTransactionIsolationLevel() | Sets the isolation level of the current transaction. | yii\ |
| supportsSavepoint() | yii\ |
|
| unquoteSimpleColumnName() | Unquotes a simple column name. | yii\ |
| unquoteSimpleTableName() | Unquotes a simple table name. | yii\ |
Protected Methods
| Method | Description | Defined By |
|---|---|---|
| createColumnSchema() | Creates a column schema for the database. | yii\ |
| findColumns() | Collects the metadata of table columns. | yii\ |
| findForeignKeys() | Collects the foreign key column details for the given table. | yii\ |
| findPrimaryKeys() | Collects the primary key column details for the given table. | yii\ |
| findSchemaNames() | Returns all schema names in the database, including the default one but not system schemas. | yii\ |
| findTableConstraints() | Collects the constraint details for the given table and constraint type. | yii\ |
| findTableNames() | Returns all table names in the database. | yii\ |
| findViewNames() | yii\ |
|
| getCacheKey() | Returns the cache key for the specified table name. | yii\ |
| getCacheTag() | Returns the cache tag name. | yii\ |
| getColumnPhpType() | Extracts the PHP type from abstract DB type. | yii\ |
| getSchemaMetadata() | Returns the metadata of the given type for all tables in the given schema. | yii\ |
| getTableMetadata() | Returns the metadata of the given type for the given table. | yii\ |
| getTableNameParts() | Splits full table name into parts. | yii\ |
| loadColumnSchema() | Loads the column information into a {@see ColumnSchema} object. | yii\ |
| loadTableChecks() | yii\ |
|
| loadTableDefaultValues() | yii\ |
|
| loadTableForeignKeys() | yii\ |
|
| loadTableIndexes() | yii\ |
|
| loadTablePrimaryKey() | yii\ |
|
| loadTableSchema() | Loads the metadata for the specified table. | yii\ |
| loadTableUniques() | yii\ |
|
| normalizePdoRowKeyCase() | Changes row's array key case to lower if PDO's one is set to uppercase. | yii\ |
| resolveTableName() | Resolves the table name and schema name (if any). | yii\ |
| setTableMetadata() | Sets the metadata of the given type for the given table. | yii\ |
Constants
| Constant | Value | Description | Defined By |
|---|---|---|---|
| SCHEMA_CACHE_VERSION | 1 | Schema cache version, to detect incompatibilities in cached values when the data format of the cache changes. | yii\ |
| TYPE_BIGINT | 'bigint' | yii\ |
|
| TYPE_BIGPK | 'bigpk' | yii\ |
|
| TYPE_BINARY | 'binary' | yii\ |
|
| TYPE_BOOLEAN | 'boolean' | yii\ |
|
| TYPE_CHAR | 'char' | yii\ |
|
| TYPE_DATE | 'date' | yii\ |
|
| TYPE_DATETIME | 'datetime' | yii\ |
|
| TYPE_DECIMAL | 'decimal' | yii\ |
|
| TYPE_DOUBLE | 'double' | yii\ |
|
| TYPE_FLOAT | 'float' | yii\ |
|
| TYPE_INTEGER | 'integer' | yii\ |
|
| TYPE_JSON | 'json' | yii\ |
|
| TYPE_MONEY | 'money' | yii\ |
|
| TYPE_PK | 'pk' | yii\ |
|
| TYPE_SMALLINT | 'smallint' | yii\ |
|
| TYPE_STRING | 'string' | yii\ |
|
| TYPE_TEXT | 'text' | yii\ |
|
| TYPE_TIME | 'time' | yii\ |
|
| TYPE_TIMESTAMP | 'timestamp' | yii\ |
|
| TYPE_TINYINT | 'tinyint' | yii\ |
|
| TYPE_UBIGPK | 'ubigpk' | yii\ |
|
| TYPE_UPK | 'upk' | yii\ |
Property Details
Character used to quote column names. An array of 2 characters can be used in case starting and ending characters are different.
Column schema class or class config
The default schema used for the current session.
Character used to quote schema, table, etc. names. An array of 2 characters can be used in case starting and ending characters are different.
Mapping from physical column types (keys) to abstract column types (values).
'bigint' => self::TYPE_BIGINT,
'numeric' => self::TYPE_DECIMAL,
'bit' => self::TYPE_SMALLINT,
'smallint' => self::TYPE_SMALLINT,
'decimal' => self::TYPE_DECIMAL,
'smallmoney' => self::TYPE_MONEY,
'int' => self::TYPE_INTEGER,
'tinyint' => self::TYPE_TINYINT,
'money' => self::TYPE_MONEY,
'float' => self::TYPE_FLOAT,
'double' => self::TYPE_DOUBLE,
'real' => self::TYPE_FLOAT,
'date' => self::TYPE_DATE,
'datetimeoffset' => self::TYPE_DATETIME,
'datetime2' => self::TYPE_DATETIME,
'smalldatetime' => self::TYPE_DATETIME,
'datetime' => self::TYPE_DATETIME,
'time' => self::TYPE_TIME,
'char' => self::TYPE_CHAR,
'varchar' => self::TYPE_STRING,
'text' => self::TYPE_TEXT,
'nchar' => self::TYPE_CHAR,
'nvarchar' => self::TYPE_STRING,
'ntext' => self::TYPE_TEXT,
'binary' => self::TYPE_BINARY,
'varbinary' => self::TYPE_BINARY,
'image' => self::TYPE_BINARY,
'timestamp' => self::TYPE_TIMESTAMP,
'hierarchyid' => self::TYPE_STRING,
'uniqueidentifier' => self::TYPE_STRING,
'sql_variant' => self::TYPE_STRING,
'xml' => self::TYPE_STRING,
'table' => self::TYPE_STRING,
]
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.
The default implementation does two things:
- Initializes the object with the given configuration
$config. - Call init().
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$confighere. - call the parent implementation at the end of the constructor.
| public mixed __construct ( array | ||
| $config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
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\
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);
}
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\
Converts a DB exception to a more concrete one if possible.
| public yii\ | ||
| $e | Exception | |
| $rawSql | string |
SQL that produced exception |
public function convertException(\Exception $e, $rawSql)
{
if ($e instanceof Exception) {
return $e;
}
$exceptionClass = '\yii\db\Exception' ;
foreach ($this->exceptionMap as $error => $class) {
if (strpos($e->getMessage(), $error) !== false) {
$exceptionClass = $class;
}
}
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql" ;
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
return new $exceptionClass($message, $errorInfo, $e->getCode(), $e);
}
Defined in:
yii\
Creates a column schema for the database.
This method may be overridden by child classes to create a DBMS-specific column schema.
| protected \ | ||
| return | \ |
Column schema instance. |
|---|---|---|
| throws | yii\ |
if a column schema class cannot be created. |
protected function createColumnSchema()
{
return Yii::createObject($this->columnSchemaClass);
}
Create a column schema builder instance giving the type and value precision.
This method may be overridden by child classes to create a DBMS-specific column schema builder.
| public yii\ | ||
| $type | mixed |
Type of the column. See yii\ |
| $length | mixed |
Length or precision of the column. See yii\ |
| return | yii\ |
Column schema builder instance |
|---|---|---|
public function createColumnSchemaBuilder($type, $length = null)
{
return Yii::createObject(ColumnSchemaBuilder::class, [$type, $length, $this->db]);
}
Creates a query builder for the MSSQL database.
| public yii\ | ||
| return | yii\ |
Query builder interface. |
|---|---|---|
public function createQueryBuilder()
{
return Yii::createObject(QueryBuilder::class, [$this->db]);
}
Creates a new savepoint.
| public mixed createSavepoint ( mixed $name ) | ||
| $name | mixed |
The savepoint name |
public function createSavepoint($name)
{
$this->db->createCommand("SAVE TRANSACTION $name")->execute();
}
Collects the metadata of table columns.
| protected boolean findColumns ( yii\ | ||
| $table | yii\ |
The table metadata. |
| return | boolean |
Whether the table exists in the database. |
|---|---|---|
protected function findColumns($table)
{
$systemCatalogName = $this->quoteSystemCatalogName($table->catalogName);
$sql = <<<SQL
SELECT
[c].[name] AS [column_name],
CASE WHEN [c].[is_nullable] = 1 THEN 'YES' ELSE 'NO' END AS [is_nullable],
CASE
WHEN [t].[name] IN ('char','varchar','nchar','nvarchar','binary','varbinary') THEN
CASE
WHEN [c].[max_length] = -1 AND [t].[name] IN ('varchar','nvarchar','varbinary') THEN
[t].[name] + '(max)'
WHEN [t].[name] IN ('nchar','nvarchar') THEN
[t].[name] + '(' + CAST([c].[max_length] / 2 AS VARCHAR) + ')'
ELSE
[t].[name] + '(' + CAST([c].[max_length] AS VARCHAR) + ')'
END
WHEN [t].[name] IN ('decimal','numeric') THEN
[t].[name] + '(' + CAST([c].[precision] AS VARCHAR) + ',' + CAST([c].[scale] AS VARCHAR) + ')'
ELSE [t].[name]
END AS [data_type],
[dc].[definition] AS [column_default],
[c].[is_identity],
[c].[is_computed],
CAST([ep].[value] AS NVARCHAR(MAX)) AS [comment]
FROM {$systemCatalogName}.[columns] AS [c]
INNER JOIN {$systemCatalogName}.[types] AS [t]
ON [c].[system_type_id] = [t].[system_type_id]
AND [t].[user_type_id] = [t].[system_type_id]
LEFT JOIN {$systemCatalogName}.[default_constraints] AS [dc]
ON [dc].[object_id] = [c].[default_object_id]
LEFT JOIN {$systemCatalogName}.[extended_properties] AS [ep]
ON [ep].[major_id] = [c].[object_id]
AND [ep].[minor_id] = [c].[column_id]
AND [ep].[class] = 1
AND [ep].[name] = 'MS_Description'
WHERE [c].[object_id] = OBJECT_ID(:fullName)
ORDER BY [c].[column_id]
SQL;
$columns = $this->db->createCommand(
$sql,
[':fullName' => $this->quoteTableFullName($table)],
)->queryAll();
if (empty($columns)) {
return false;
}
foreach ($columns as $column) {
$column = $this->loadColumnSchema($column);
foreach ($table->primaryKey as $primaryKey) {
if (strcasecmp($column->name, $primaryKey) === 0) {
$column->isPrimaryKey = true;
break;
}
}
if ($column->isPrimaryKey && $column->autoIncrement) {
$table->sequenceName = '';
}
$column->defaultValue = $column->isPrimaryKey && $column->autoIncrement
? null
: $column->defaultPhpTypecast($column->defaultValue);
$table->columns[$column->name] = $column;
}
return true;
}
Collects the foreign key column details for the given table.
| protected mixed findForeignKeys ( yii\ | ||
| $table | yii\ |
The table metadata |
protected function findForeignKeys($table)
{
$systemCatalogName = $this->quoteSystemCatalogName($table->catalogName);
$databaseId = $this->getDatabaseIdExpression($table);
$sql = <<<SQL
SELECT
[fk].[name] AS [fk_name],
[cp].[name] AS [fk_column_name],
OBJECT_NAME([fk].[referenced_object_id], {$databaseId}) AS [uq_table_name],
[cr].[name] AS [uq_column_name]
FROM
{$systemCatalogName}.[foreign_keys] AS [fk]
INNER JOIN {$systemCatalogName}.[foreign_key_columns] AS [fkc] ON
[fk].[object_id] = [fkc].[constraint_object_id]
INNER JOIN {$systemCatalogName}.[columns] AS [cp] ON
[fk].[parent_object_id] = [cp].[object_id] AND
[fkc].[parent_column_id] = [cp].[column_id]
INNER JOIN {$systemCatalogName}.[columns] AS [cr] ON
[fk].[referenced_object_id] = [cr].[object_id] AND
[fkc].[referenced_column_id] = [cr].[column_id]
WHERE
[fk].[parent_object_id] = OBJECT_ID(:object)
SQL;
$rows = $this->db->createCommand(
$sql,
[':object' => $this->quoteTableFullName($table)],
)->queryAll();
$table->foreignKeys = [];
foreach ($rows as $row) {
if (!isset($table->foreignKeys[$row['fk_name']])) {
$table->foreignKeys[$row['fk_name']][] = $row['uq_table_name'];
}
$table->foreignKeys[$row['fk_name']][$row['fk_column_name']] = $row['uq_column_name'];
}
}
Collects the primary key column details for the given table.
| protected mixed findPrimaryKeys ( yii\ | ||
| $table | yii\ |
The table metadata |
protected function findPrimaryKeys($table)
{
$result = [];
foreach ($this->findTableConstraints($table, 'PK') as $row) {
$result[] = $row['field_name'];
}
$table->primaryKey = $result;
}
Returns all schema names in the database, including the default one but not system schemas.
This method should be overridden by child classes in order to support this feature because the default implementation simply throws an exception.
| protected array findSchemaNames ( ) | ||
| return | array |
All schema names in the database, except system schemas. |
|---|---|---|
| throws | yii\ |
if this method is not supported by the DBMS. |
protected function findSchemaNames()
{
$systemSchemaNames = "'"
. implode("', '", array_map([Quoter::class, 'escapeLiteralValue'], $this->systemSchemaNames))
. "'";
$sql = <<<SQL
SELECT [s].[name]
FROM [sys].[schemas] AS [s]
INNER JOIN [sys].[database_principals] AS [p] ON [p].[principal_id] = [s].[principal_id]
WHERE [p].[is_fixed_role] = 0
AND [p].[sid] IS NOT NULL
AND [s].[name] NOT IN ({$systemSchemaNames})
ORDER BY [s].[name] ASC
SQL;
return $this->db->createCommand(
$sql,
)->queryColumn();
}
Collects the constraint details for the given table and constraint type.
| protected array findTableConstraints ( yii\ | ||
| $table | yii\ |
The table metadata. |
| $type | string |
Either |
| return | array |
Each entry contains index_name and field_name. |
|---|---|---|
protected function findTableConstraints($table, $type)
{
$systemCatalogName = $this->quoteSystemCatalogName($table->catalogName);
$sql = <<<SQL
SELECT
[kc].[name] AS [index_name],
[col].[name] AS [field_name]
FROM {$systemCatalogName}.[key_constraints] AS [kc]
INNER JOIN {$systemCatalogName}.[index_columns] AS [ic]
ON [ic].[object_id] = [kc].[parent_object_id]
AND [ic].[index_id] = [kc].[unique_index_id]
INNER JOIN {$systemCatalogName}.[columns] AS [col]
ON [col].[object_id] = [ic].[object_id]
AND [col].[column_id] = [ic].[column_id]
WHERE [kc].[parent_object_id] = OBJECT_ID(:fullName)
AND [kc].[type] = :type
ORDER BY [ic].[key_ordinal] ASC
SQL;
return $this->db->createCommand(
$sql,
[
':fullName' => $this->quoteTableFullName($table),
':type' => $type,
],
)->queryAll();
}
Returns all table names in the database.
This method should be overridden by child classes in order to support this feature because the default implementation simply throws an exception.
| protected array findTableNames ( mixed $schema = '' ) | ||
| $schema | mixed |
The schema of the tables. Defaults to empty string, meaning the current or default schema. |
| return | array |
All table names in the database. The names have NO schema name prefix. |
|---|---|---|
| throws | yii\ |
if this method is not supported by the DBMS. |
protected function findTableNames($schema = '')
{
[$catalogName, $schemaName] = $this->resolveCatalogSchemaName($schema);
$systemCatalogName = $this->quoteSystemCatalogName($catalogName);
$sql = <<<SQL
SELECT [o].[name]
FROM {$systemCatalogName}.[objects] AS [o]
INNER JOIN {$systemCatalogName}.[schemas] AS [s] ON [s].[schema_id] = [o].[schema_id]
WHERE [s].[name] = :schema
AND [o].[type] IN ('U', 'V')
ORDER BY [o].[name]
SQL;
return $this->db->createCommand(
$sql,
[':schema' => $schemaName],
)->queryColumn();
}
Returns all unique indexes for the given table.
Each array element is of the following structure:
[
'IndexName1' => ['col1' [, ...]],
'IndexName2' => ['col2' [, ...]],
]
| public array findUniqueIndexes ( yii\ | ||
| $table | yii\ |
The table metadata. |
| return | array |
All unique indexes for the given table. |
|---|---|---|
public function findUniqueIndexes($table)
{
$result = [];
foreach ($this->findTableConstraints($table, 'UQ') as $row) {
$result[$row['index_name']][] = $row['field_name'];
}
return $result;
}
| protected findViewNames ( mixed $schema = '' ) | ||
| $schema | mixed | |
protected function findViewNames($schema = '')
{
[$catalogName, $schemaName] = $this->resolveCatalogSchemaName($schema);
$systemCatalogName = $this->quoteSystemCatalogName($catalogName);
$sql = <<<SQL
SELECT [v].[name]
FROM {$systemCatalogName}.[views] AS [v]
INNER JOIN {$systemCatalogName}.[schemas] AS [s] ON [s].[schema_id] = [v].[schema_id]
WHERE [s].[name] = :schema
ORDER BY [v].[name]
SQL;
return $this->db->createCommand(
$sql,
[':schema' => $schemaName],
)->queryColumn();
}
Defined in:
yii\
Returns the cache key for the specified table name.
| protected mixed getCacheKey ( string $name ) | ||
| $name | string |
The table name. |
| return | mixed |
The cache key. |
|---|---|---|
protected function getCacheKey($name)
{
return [
__CLASS__,
$this->db->dsn,
$this->db->username,
$this->getRawTableName($name),
];
}
Defined in:
yii\
Returns the cache tag name.
This allows refresh() to invalidate all cached table schemas.
| protected string getCacheTag ( ) | ||
| return | string |
The cache tag name |
|---|---|---|
protected function getCacheTag()
{
return md5(serialize([
__CLASS__,
$this->db->dsn,
$this->db->username,
]));
}
Defined in:
yii\
Extracts the PHP type from abstract DB type.
| protected string getColumnPhpType ( yii\ | ||
| $column | yii\ |
The column schema information |
| return | string |
PHP type name |
|---|---|---|
protected function getColumnPhpType($column)
{
static $typeMap = [
// abstract type => php type
self::TYPE_TINYINT => 'integer',
self::TYPE_SMALLINT => 'integer',
self::TYPE_INTEGER => 'integer',
self::TYPE_BIGINT => 'integer',
self::TYPE_BOOLEAN => 'boolean',
self::TYPE_FLOAT => 'double',
self::TYPE_DOUBLE => 'double',
self::TYPE_BINARY => 'resource',
self::TYPE_JSON => 'array',
];
if (isset($typeMap[$column->type])) {
if ($column->type === 'bigint') {
return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string';
} elseif ($column->type === 'integer') {
return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer';
}
return $typeMap[$column->type];
}
return 'string';
}
Defined in:
yii\
Returns the ID of the last inserted row or sequence value.
See also https://www.php.net/manual/en/function.PDO-lastInsertId.php.
| public string getLastInsertID ( string $sequenceName = '' ) | ||
| $sequenceName | string |
Name of the sequence object (required by some DBMS) |
| return | string |
The row ID of the last row inserted, or the last value retrieved from the sequence object |
|---|---|---|
| throws | yii\ |
if the DB connection is not active |
public function getLastInsertID($sequenceName = '')
{
if ($this->db->isActive) {
return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName));
}
throw new InvalidCallException('DB Connection is not active.');
}
Defined in:
yii\
Determines the PDO type for the given PHP data value.
| public integer getPdoType ( mixed $data ) | ||
| $data | mixed |
The data whose PDO type is to be determined |
| return | integer |
The PDO type |
|---|---|---|
public function getPdoType($data)
{
static $typeMap = [
// php type => PDO type
'boolean' => \PDO::PARAM_BOOL,
'integer' => \PDO::PARAM_INT,
'string' => \PDO::PARAM_STR,
'resource' => \PDO::PARAM_LOB,
'NULL' => \PDO::PARAM_NULL,
];
$type = gettype($data);
return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
}
Defined in:
yii\
| public \ | ||
| return | \ |
The query builder for this connection. |
|---|---|---|
public function getQueryBuilder()
{
if ($this->_builder === null) {
$this->_builder = $this->createQueryBuilder();
}
return $this->_builder;
}
Defined in:
yii\
Returns the actual name of a given table name.
This method will strip off curly brackets from the given table name
and replace the percentage character '%' with yii\
| public string getRawTableName ( string $name ) | ||
| $name | string |
The table name to be converted |
| return | string |
The real name of the given table name |
|---|---|---|
public function getRawTableName($name)
{
if (strpos($name, '{{') !== false) {
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
return str_replace('%', $this->db->tablePrefix, $name);
}
return $name;
}
Defined in:
yii\
Returns check constraints for all tables in the database.
| public \ | ||
| $schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. |
| $refresh | boolean |
Whether to fetch the latest available table schemas. If this is false, cached data may be returned if available. |
| return | \ |
Check constraints for all tables in the database.
Each array element is an array of yii\ |
|---|---|---|
public function getSchemaChecks($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'checks', $refresh);
}
Defined in:
yii\
Returns default value constraints for all tables in the database.
| public yii\ | ||
| $schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. |
| $refresh | boolean |
Whether to fetch the latest available table schemas. If this is false, cached data may be returned if available. |
| return | yii\ |
Default value constraints for all tables in the database.
Each array element is an array of yii\ |
|---|---|---|
public function getSchemaDefaultValues($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'defaultValues', $refresh);
}
Defined in:
yii\
Returns foreign keys for all tables in the database.
| public \ | ||
| $schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. |
| $refresh | boolean |
Whether to fetch the latest available table schemas. If this is false, cached data may be returned if available. |
| return | \ |
Foreign keys for all tables in the database.
Each array element is an array of yii\ |
|---|---|---|
public function getSchemaForeignKeys($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'foreignKeys', $refresh);
}
Defined in:
yii\
Returns indexes for all tables in the database.
| public \ | ||
| $schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. |
| $refresh | boolean |
Whether to fetch the latest available table schemas. If this is false, cached data may be returned if available. |
| return | \ |
Indexes for all tables in the database.
Each array element is an array of yii\ |
|---|---|---|
public function getSchemaIndexes($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'indexes', $refresh);
}
Returns the metadata of the given type for all tables in the given schema.
This method will call a 'getTable' . ucfirst($type) named method with the table name
and the refresh flag to obtain the metadata.
| protected array getSchemaMetadata ( mixed $schema, mixed $type, mixed $refresh ) | ||
| $schema | mixed |
The schema of the metadata. Defaults to empty string, meaning the current or default schema name. |
| $type | mixed |
Metadata type. |
| $refresh | mixed |
Whether to fetch the latest available table metadata. If this is |
| return | array |
Array of metadata. |
|---|---|---|
protected function getSchemaMetadata($schema, $type, $refresh)
{
$metadata = [];
$methodName = 'getTable' . ucfirst($type);
$tableNames = array_map(
fn (string $table): string => $this->quoteSimpleTableName($table),
$this->getTableNames($schema, $refresh),
);
foreach ($tableNames as $name) {
if ($schema !== '') {
$name = "{$schema}.{$name}";
}
$tableMetadata = $this->$methodName($name, $refresh);
if ($tableMetadata !== null) {
$metadata[] = $tableMetadata;
}
}
return $metadata;
}
Defined in:
yii\
Returns all schema names in the database, except system schemas.
| public string[] getSchemaNames ( boolean $refresh = false ) | ||
| $refresh | boolean |
Whether to fetch the latest available schema names. If this is false, schema names fetched previously (if available) will be returned. |
| return | string[] |
All schema names in the database, except system schemas. |
|---|---|---|
public function getSchemaNames($refresh = false)
{
if ($this->_schemaNames === null || $refresh) {
$this->_schemaNames = $this->findSchemaNames();
}
return $this->_schemaNames;
}
Defined in:
yii\
Returns primary keys for all tables in the database.
| public yii\ | ||
| $schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. |
| $refresh | boolean |
Whether to fetch the latest available table schemas. If this is |
| return | yii\ |
Primary keys for all tables in the database.
Each array element is an instance of yii\ |
|---|---|---|
public function getSchemaPrimaryKeys($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'primaryKey', $refresh);
}
Defined in:
yii\
Returns unique constraints for all tables in the database.
| public \ | ||
| $schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. |
| $refresh | boolean |
Whether to fetch the latest available table schemas. If this is false, cached data may be returned if available. |
| return | \ |
Unique constraints for all tables in the database.
Each array element is an array of yii\ |
|---|---|---|
public function getSchemaUniques($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'uniques', $refresh);
}
Defined in:
yii\
Returns a server version as a string comparable by \
| public string getServerVersion ( ) | ||
| return | string |
Server version as a string. |
|---|---|---|
public function getServerVersion()
{
if ($this->_serverVersion === null) {
$this->_serverVersion = $this->db->getSlavePdo(true)->getAttribute(\PDO::ATTR_SERVER_VERSION);
}
return $this->_serverVersion;
}
Defined in:
yii\
Obtains the check constraints information for the named table.
| public yii\ | ||
| $name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
| $refresh | boolean |
Whether to reload the information even if it is found in the cache. |
| return | yii\ |
Table check constraints. |
|---|---|---|
public function getTableChecks($name, $refresh = false)
{
return $this->getTableMetadata($name, 'checks', $refresh);
}
Defined in:
yii\
Obtains the default value constraints information for the named table.
| public yii\ | ||
| $name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
| $refresh | boolean |
Whether to reload the information even if it is found in the cache. |
| return | yii\ |
Table default value constraints. |
|---|---|---|
public function getTableDefaultValues($name, $refresh = false)
{
return $this->getTableMetadata($name, 'defaultValues', $refresh);
}
Defined in:
yii\
Obtains the foreign keys information for the named table.
| public yii\ | ||
| $name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
| $refresh | boolean |
Whether to reload the information even if it is found in the cache. |
| return | yii\ |
Table foreign keys. |
|---|---|---|
public function getTableForeignKeys($name, $refresh = false)
{
return $this->getTableMetadata($name, 'foreignKeys', $refresh);
}
Defined in:
yii\
Obtains the indexes information for the named table.
| public yii\ | ||
| $name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
| $refresh | boolean |
Whether to reload the information even if it is found in the cache. |
| return | yii\ |
Table indexes. |
|---|---|---|
public function getTableIndexes($name, $refresh = false)
{
return $this->getTableMetadata($name, 'indexes', $refresh);
}
Defined in:
yii\
Returns the metadata of the given type for the given table.
If there's no metadata in the cache, this method will call
a 'loadTable' . ucfirst($type) named method with the table name to obtain the metadata.
| protected mixed getTableMetadata ( string $name, string $type, boolean $refresh ) | ||
| $name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
| $type | string |
Metadata type. |
| $refresh | boolean |
Whether to reload the table metadata even if it is found in the cache. |
| return | mixed |
Metadata. |
|---|---|---|
protected function getTableMetadata($name, $type, $refresh)
{
$cache = null;
if ($this->db->enableSchemaCache && !in_array($name, $this->db->schemaCacheExclude, true)) {
$schemaCache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($schemaCache instanceof CacheInterface) {
$cache = $schemaCache;
}
}
$rawName = $this->getRawTableName($name);
if (!isset($this->_tableMetadata[$rawName])) {
$this->loadTableMetadataFromCache($cache, $rawName);
}
if ($refresh || !array_key_exists($type, $this->_tableMetadata[$rawName])) {
$this->_tableMetadata[$rawName][$type] = $this->{'loadTable' . ucfirst($type)}($rawName);
$this->saveTableMetadataToCache($cache, $rawName);
}
return $this->_tableMetadata[$rawName][$type];
}
Splits full table name into parts.
| protected array getTableNameParts ( mixed $name ) | ||
| $name | mixed |
Full table name. |
| return | array |
Table name parts. |
|---|---|---|
protected function getTableNameParts($name)
{
preg_match_all('/([^.\[\]]+)|\[([^\[\]]+)\]/', $name, $matches);
$parts = $matches[0] === [] ? [$name] : $matches[0];
return str_replace(['[', ']'], '', $parts);
}
Defined in:
yii\
Returns all table names in the database.
| public string[] getTableNames ( string $schema = '', boolean $refresh = false ) | ||
| $schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. If not empty, the returned table names will be prefixed with the schema name. |
| $refresh | boolean |
Whether to fetch the latest available table names. If this is false, table names fetched previously (if available) will be returned. |
| return | string[] |
All table names in the database. |
|---|---|---|
public function getTableNames($schema = '', $refresh = false)
{
if (!isset($this->_tableNames[$schema]) || $refresh) {
$this->_tableNames[$schema] = $this->findTableNames($schema);
}
return $this->_tableNames[$schema];
}
Defined in:
yii\
Obtains the primary key for the named table.
| public yii\ | ||
| $name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
| $refresh | boolean |
Whether to reload the information even if it is found in the cache. |
| return | yii\ |
Table primary key, |
|---|---|---|
public function getTablePrimaryKey($name, $refresh = false)
{
return $this->getTableMetadata($name, 'primaryKey', $refresh);
}
Defined in:
yii\
Obtains the metadata for the named table.
| public yii\ | ||
| $name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
| $refresh | boolean |
Whether to reload the table schema even if it is found in the cache. |
| return | yii\ |
Table metadata. |
|---|---|---|
public function getTableSchema($name, $refresh = false)
{
return $this->getTableMetadata($name, 'schema', $refresh);
}
Defined in:
yii\
Returns the metadata for all tables in the database.
| public yii\ | ||
| $schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. |
| $refresh | boolean |
Whether to fetch the latest available table schemas. If this is |
| return | yii\ |
The metadata for all tables in the database.
Each array element is an instance of yii\ |
|---|---|---|
public function getTableSchemas($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'schema', $refresh);
}
Defined in:
yii\
Obtains the unique constraints information for the named table.
| public yii\ | ||
| $name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
| $refresh | boolean |
Whether to reload the information even if it is found in the cache. |
| return | yii\ |
Table unique constraints. |
|---|---|---|
public function getTableUniques($name, $refresh = false)
{
return $this->getTableMetadata($name, 'uniques', $refresh);
}
Defined in:
yii\
Returns all view names in the database.
| public string[] getViewNames ( string $schema = '', boolean $refresh = false ) | ||
| $schema | string |
The schema of the views. Defaults to empty string, meaning the current or default schema name. If not empty, the returned view names will be prefixed with the schema name. |
| $refresh | boolean |
Whether to fetch the latest available view names. If this is false, view names fetched previously (if available) will be returned. |
| return | string[] |
All view names in the database. |
|---|---|---|
public function getViewNames($schema = '', $refresh = false)
{
if (!isset($this->_viewNames[$schema]) || $refresh) {
$this->_viewNames[$schema] = $this->findViewNames($schema);
}
return $this->_viewNames[$schema];
}
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\
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()
{
}
Executes the INSERT command, returning primary key values.
Retrieves the inserted row via the OUTPUT INSERTED.* block emitted by \ so
that IDENTITY values, computed columns, and uniqueidentifier defaults are returned to the caller.
| public array|false insert ( mixed $table, mixed $columns ) | ||
| $table | mixed |
The table that new rows will be inserted into. |
| $columns | mixed |
The column data (name => value) to be inserted into the table. |
| return | array|false |
Primary key values or false if the command fails |
|---|---|---|
public function insert($table, $columns)
{
$command = $this->db->createCommand()->insert($table, $columns);
if (!$command->execute()) {
return false;
}
$inserted = $command->pdoStatement->fetch();
$tableSchema = $this->getTableSchema($table);
$result = [];
foreach ($tableSchema->primaryKey as $name) {
// @see https://github.com/yiisoft/yii2/issues/13828 & https://github.com/yiisoft/yii2/issues/17474
if (isset($inserted[$name])) {
$result[$name] = $inserted[$name];
} elseif (isset($columns[$name])) {
$result[$name] = $columns[$name];
} else {
$result[$name] = $tableSchema->columns[$name]->defaultValue;
}
}
return $result;
}
Defined in:
yii\
Returns a value indicating whether a SQL statement is for read purpose.
| public boolean isReadQuery ( string $sql ) | ||
| $sql | string |
The SQL statement |
| return | boolean |
Whether a SQL statement is for read purpose. |
|---|---|---|
public function isReadQuery($sql)
{
$pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i' ;
return preg_match($pattern, $sql) > 0;
}
Loads the column information into a {@see ColumnSchema} object.
| protected \ | ||
| $info | array |
Column information. |
| return | \ |
The column schema object. |
|---|---|---|
protected function loadColumnSchema($info)
{
$column = $this->createColumnSchema();
$column->name = $info['column_name'];
$column->allowNull = $info['is_nullable'] === 'YES';
$column->dbType = $info['data_type'];
$column->enumValues = []; // MSSQL has only vague equivalents to enum.
$column->isPrimaryKey = null; // Primary key will be determined in `findColumns()` method.
$column->autoIncrement = (bool) $info['is_identity'];
$column->isComputed = (bool) $info['is_computed'];
$column->comment = $info['comment'] === null ? '' : $info['comment'];
$column->type = self::TYPE_STRING;
if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/' , $column->dbType, $matches)) {
$type = $matches[1];
if (isset($this->typeMap[$type])) {
$column->type = $this->typeMap[$type];
}
if ($type === 'bit') {
$column->type = self::TYPE_BOOLEAN;
}
if (!empty($matches[2]) && strcasecmp($matches[2], 'max') !== 0) {
$values = explode(',', $matches[2]);
$column->size = $column->precision = (int) $values[0];
if (isset($values[1])) {
$column->scale = (int) $values[1];
}
}
}
$column->phpType = $this->getColumnPhpType($column);
// Store raw default for deferred resolution in `findColumns()`, where isPrimaryKey is known.
$column->defaultValue = $info['column_default'];
return $column;
}
| protected loadTableChecks ( mixed $tableName ) | ||
| $tableName | mixed | |
protected function loadTableChecks($tableName)
{
return $this->loadTableConstraints($tableName, 'checks');
}
| protected loadTableDefaultValues ( mixed $tableName ) | ||
| $tableName | mixed | |
protected function loadTableDefaultValues($tableName)
{
return $this->loadTableConstraints($tableName, 'defaults');
}
| protected loadTableForeignKeys ( mixed $tableName ) | ||
| $tableName | mixed | |
protected function loadTableForeignKeys($tableName)
{
return $this->loadTableConstraints($tableName, 'foreignKeys');
}
| protected loadTableIndexes ( mixed $tableName ) | ||
| $tableName | mixed | |
protected function loadTableIndexes($tableName)
{
$resolvedName = $this->resolveTableName($tableName);
$systemCatalogName = $this->quoteSystemCatalogName($resolvedName->catalogName);
$sql = <<<SQL
SELECT
[i].[name] AS [name],
[iccol].[name] AS [column_name],
[i].[is_unique] AS [index_is_unique],
[i].[is_primary_key] AS [index_is_primary]
FROM {$systemCatalogName}.[indexes] AS [i]
INNER JOIN {$systemCatalogName}.[index_columns] AS [ic]
ON [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id]
INNER JOIN {$systemCatalogName}.[columns] AS [iccol]
ON [iccol].[object_id] = [ic].[object_id] AND [iccol].[column_id] = [ic].[column_id]
WHERE [i].[object_id] = OBJECT_ID(:fullName)
ORDER BY [ic].[key_ordinal] ASC
SQL;
$indexes = $this->db->createCommand(
$sql,
[':fullName' => $this->quoteTableFullName($resolvedName)],
)->queryAll();
$indexes = $this->normalizePdoRowKeyCase($indexes, true);
$indexes = ArrayHelper::index($indexes, null, 'name');
$result = [];
foreach ($indexes as $name => $index) {
$result[] = new IndexConstraint(
[
'isPrimary' => (bool) $index[0]['index_is_primary'],
'isUnique' => (bool) $index[0]['index_is_unique'],
'name' => $name,
'columnNames' => ArrayHelper::getColumn($index, 'column_name'),
],
);
}
return $result;
}
| protected loadTablePrimaryKey ( mixed $tableName ) | ||
| $tableName | mixed | |
protected function loadTablePrimaryKey($tableName)
{
return $this->loadTableConstraints($tableName, 'primaryKey');
}
Loads the metadata for the specified table.
| protected yii\ | ||
| $name | mixed |
Table name |
| return | yii\ |
DBMS-dependent table metadata, |
|---|---|---|
protected function loadTableSchema($name)
{
$table = $this->resolveTableName($name);
$this->findPrimaryKeys($table);
if ($this->findColumns($table)) {
$this->findForeignKeys($table);
return $table;
}
return null;
}
| protected loadTableUniques ( mixed $tableName ) | ||
| $tableName | mixed | |
protected function loadTableUniques($tableName)
{
return $this->loadTableConstraints($tableName, 'uniques');
}
Defined in:
yii\
Changes row's array key case to lower if PDO's one is set to uppercase.
| protected array normalizePdoRowKeyCase ( array $row, boolean $multiple ) | ||
| $row | array |
Row's array or an array of row's arrays. |
| $multiple | boolean |
Whether multiple rows or a single row passed. |
| return | array |
Normalized row or rows. |
|---|---|---|
protected function normalizePdoRowKeyCase(array $row, $multiple)
{
if ($this->db->getSlavePdo(true)->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_UPPER) {
return $row;
}
if ($multiple) {
return array_map(function (array $row) {
return array_change_key_case($row, CASE_LOWER);
}, $row);
}
return array_change_key_case($row, CASE_LOWER);
}
Quotes a column name for use in a query.
If the column name contains prefix, the prefix will also be properly quoted. If the column name is already fully enclosed in the quote characters, or contains '(', '[[' or '{{', then this method will do nothing.
| public string quoteColumnName ( mixed $name ) | ||
| $name | mixed |
Column name. |
| return | string |
The properly quoted column name. |
|---|---|---|
public function quoteColumnName($name)
{
if (Quoter::isIdentifierBracketQuoted($name)) {
return $name;
}
return parent::quoteColumnName($name);
}
Defined in:
yii\
Quotes a simple column name for use in a query.
A simple column name should contain the column name only without any prefix. The asterisk character '*' and a name already fully enclosed in the quote characters are returned as is; otherwise the name is enclosed and any embedded ending quote character is escaped by doubling it.
| public string quoteSimpleColumnName ( string $name ) | ||
| $name | string |
Column name. |
| return | string |
The properly quoted column name. |
|---|---|---|
public function quoteSimpleColumnName($name)
{
if ($name === '*') {
return $name;
}
return $this->quoteSimpleName($name, $this->columnQuoteCharacter);
}
Defined in:
yii\
Quotes a simple table name for use in a query.
A simple table name should contain the table name only without any schema prefix. A name already fully enclosed in the quote characters is returned as is; otherwise the name is enclosed and any embedded ending quote character is escaped by doubling it.
| public string quoteSimpleTableName ( string $name ) | ||
| $name | string |
Table name. |
| return | string |
The properly quoted table name. |
|---|---|---|
public function quoteSimpleTableName($name)
{
return $this->quoteSimpleName($name, $this->tableQuoteCharacter);
}
Quotes the [sys] system catalog name, optionally qualified by the database catalog.
| public string quoteSystemCatalogName ( string|null $catalogName ) | ||
| $catalogName | string|null |
The database catalog name, or |
| return | string |
The |
|---|---|---|
public function quoteSystemCatalogName(string|null $catalogName): string
{
return $this->quoteTableNameParts([$catalogName, 'sys']);
}
Qualifies single-part table names with {@see $defaultSchema} when it differs from 'dbo', ensuring
unqualified DDL and DML statements target the configured schema rather than the SQL Server login default.
| public mixed quoteTableName ( mixed $name ) | ||
| $name | mixed | |
public function quoteTableName($name)
{
if (
$this->defaultSchema !== 'dbo'
&& !str_starts_with($name, '(')
&& !str_contains($name, '{{')
&& !str_contains($name, '.')
) {
$name = "{$this->defaultSchema}.$name";
}
return parent::quoteTableName($name);
}
Defined in:
yii\
Quotes a string value for use in a query.
Note that if the parameter is not a string, it will be returned without change.
See also https://www.php.net/manual/en/function.PDO-quote.php.
| public mixed quoteValue ( mixed $str ) | ||
| $str | mixed |
String to be quoted. If the parameter is not a string, it will be returned without change. |
| return | mixed |
The properly quoted string, or the original data if it is not a string. |
|---|---|---|
public function quoteValue($str)
{
if (!is_string($str)) {
return $str;
}
if (
mb_stripos((string)$this->db->dsn, 'odbc:') === false &&
($value = $this->db->getSlavePdo(true)->quote($str)
) !== false
) {
return $value;
}
// The driver doesn't support quote (for example, oci).
return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032" ) . "'";
}
Defined in:
yii\
Refreshes the schema.
This method cleans up all cached table schemas so that they can be re-created later to reflect the database schema change.
| public mixed refresh ( ) |
public function refresh()
{
/** @var CacheInterface $cache */
$cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
TagDependency::invalidate($cache, $this->getCacheTag());
}
$this->_tableNames = [];
$this->_tableMetadata = [];
}
Defined in:
yii\
Refreshes the particular table schema.
This method cleans up cached table schema so that it can be re-created later to reflect the database schema change.
| public mixed refreshTableSchema ( string $name ) | ||
| $name | string |
Table name. |
public function refreshTableSchema($name)
{
$rawName = $this->getRawTableName($name);
unset($this->_tableMetadata[$rawName]);
$this->_tableNames = [];
/** @var CacheInterface $cache */
$cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
$cache->delete($this->getCacheKey($rawName));
}
}
Releases an existing savepoint.
| public mixed releaseSavepoint ( mixed $name ) | ||
| $name | mixed |
The savepoint name |
public function releaseSavepoint($name)
{
// Does nothing as MSSQL does not support this.
}
Resolves a schema argument into optional catalog and schema names without loading database metadata.
| public array{string|null, string} resolveRawCatalogSchemaName ( string $schema ) | ||
| $schema | string |
The schema argument. |
| return | array{string|null, string} |
The catalog and schema names. |
|---|---|---|
public function resolveRawCatalogSchemaName(string $schema): array
{
return $this->resolveCatalogSchemaName($schema);
}
Defined in:
yii\
Resolves the table name and schema name (if any) without loading database metadata.
| public yii\ | ||
| $name | string |
The table name. |
| return | yii\ |
TableSchema with resolved table, schema, etc. names. |
|---|---|---|
| throws | yii\ |
if this method is not supported by the DBMS. |
public function resolveRawTableName($name): TableSchema
{
return $this->resolveTableName($name);
}
Resolves the table name and schema name (if any).
| protected yii\ | ||
| $name | string |
The table name |
| return | yii\ |
Resolved table, schema, etc. names. |
|---|---|---|
protected function resolveTableName($name)
{
$parts = $this->getTableNameParts($name);
$partCount = count($parts);
$last = $partCount - 1;
$penultimate = $partCount - 2;
$catalogIndex = $partCount === 4 ? 1 : 0;
$tableName = $parts[$last];
$schemaName = $partCount >= 2 ? $parts[$penultimate] : $this->defaultSchema;
$catalogName = $partCount >= 3 ? $parts[$catalogIndex] : null;
$fullName = match (true) {
$catalogName !== null => "{$catalogName}.{$schemaName}.{$tableName}",
$schemaName !== $this->defaultSchema => "{$schemaName}.{$tableName}",
default => $tableName,
};
$resolvedName = new TableSchema();
$resolvedName->name = $tableName;
$resolvedName->schemaName = $schemaName;
$resolvedName->catalogName = $catalogName;
$resolvedName->fullName = $fullName;
return $resolvedName;
}
Rolls back to a previously created savepoint.
| public mixed rollBackSavepoint ( mixed $name ) | ||
| $name | mixed |
The savepoint name |
public function rollBackSavepoint($name)
{
$this->db->createCommand("ROLLBACK TRANSACTION $name")->execute();
}
Defined in:
yii\
Sets the metadata of the given type for the given table.
| protected mixed setTableMetadata ( string $name, string $type, mixed $data ) | ||
| $name | string |
Table name. |
| $type | string |
Metadata type. |
| $data | mixed |
Metadata. |
protected function setTableMetadata($name, $type, $data)
{
$this->_tableMetadata[$this->getRawTableName($name)][$type] = $data;
}
Defined in:
yii\
Sets the isolation level of the current transaction.
See also https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.
| public mixed setTransactionIsolationLevel ( string $level ) | ||
| $level | string |
The transaction isolation level to use for this transaction.
This can be one of yii\ |
public function setTransactionIsolationLevel($level)
{
$this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
}
Defined in:
yii\
| public boolean supportsSavepoint ( ) | ||
| return | boolean |
Whether this DBMS supports savepoint. |
|---|---|---|
public function supportsSavepoint()
{
return $this->db->enableSavepoint;
}
Defined in:
yii\
Unquotes a simple column name.
A simple column name should contain the column name only without any prefix. Only a name fully enclosed in the quote characters is unquoted: the enclosure is stripped and doubled ending quote characters are collapsed to a single one.
| public string unquoteSimpleColumnName ( string $name ) | ||
| $name | string |
Column name. |
| return | string |
Unquoted column name. |
|---|---|---|
public function unquoteSimpleColumnName($name)
{
return $this->unquoteSimpleName($name, $this->columnQuoteCharacter);
}
Defined in:
yii\
Unquotes a simple table name.
A simple table name should contain the table name only without any schema prefix. Only a name fully enclosed in the quote characters is unquoted: the enclosure is stripped and doubled ending quote characters are collapsed to a single one.
| public string unquoteSimpleTableName ( string $name ) | ||
| $name | string |
Table name. |
| return | string |
Unquoted table name. |
|---|---|---|
public function unquoteSimpleTableName($name)
{
return $this->unquoteSimpleName($name, $this->tableQuoteCharacter);
}
User Contributed Notes
Leave a comment
Join the conversation to share a note.