Skip to content
PHP Ecosystem
Explore

Schema

API reference › yii › db › Schema

abstract classyii\db\Schema
Extendsyii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/db/Schema.php
5 subclasses

Schema is the base class for concrete DBMS-specific schema classes.

Schema represents the database schema information that is DBMS specific.

PropertyTypeDescriptionDefined by
$columnSchemaClassclass-string<yii\db\T>|array{class?: class-string<yii\db\T>, __class?: class-string<yii\db\T>}Column schema class or class config Default: 'yii\db\ColumnSchema'. Available since 2.0.11.Schema
$dbConnectionThe database connection Default: null.Schema
$defaultSchemastringThe default schema name used for the current session. Default: null.Schema
$exceptionMaparrayMap of DB errors and corresponding exceptions If left part is found in DB error message exception class from the right part is used. Default: ['SQLSTATE[23' => 'yii\db\IntegrityException'].Schema
$lastInsertID read-onlystringThe row ID of the last row inserted, or the last value retrieved from the sequence object.Schema
$queryBuilder read-onlyyii\db\TQueryBuilderThe query builder for this connection.Schema
$schemaNames read-onlystring[]All schema names in the database, except system schemas.Schema
$serverVersion read-onlystringServer version as a string.Schema
$systemSchemaNameslist<string>List of schema names that should be excluded from getSchemaNames(). Default: [].Schema
$tableNames read-onlystring[]All table names in the database.Schema
$tableSchemas read-onlyTableSchema[]The metadata for all tables in the database.Schema
$transactionIsolationLevel write-onlystringThe transaction isolation level to use for this transaction.Schema
$columnQuoteCharacter protectedstring|string[]Character used to quote column names. Default: '"'. Available since 2.0.14.Schema
$tableQuoteCharacter protectedstring|string[]Character used to quote schema, table, etc. names. Default: "'". Available since 2.0.14.Schema
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.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
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
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
convertException()Converts a DB exception to a more concrete one if possible.Schema
createColumnSchemaBuilder()Create a column schema builder instance giving the type and value precision.Schema
createQueryBuilder()Creates a query builder for the database.Schema
createSavepoint()Creates a new savepoint.Schema
findUniqueIndexes()Returns all unique indexes for the given table.Schema
getLastInsertID()Returns the ID of the last inserted row or sequence value.Schema
getPdoType()Determines the PDO type for the given PHP data value.Schema
getQueryBuilder()Schema
getRawTableName()Returns the actual name of a given table name.Schema
getSchemaNames()Returns all schema names in the database, except system schemas.Schema
getServerVersion()Returns a server version as a string comparable by version_compare().Schema
getTableNames()Returns all table names in the database.Schema
getTableSchema()Obtains the metadata for the named table.Schema
getTableSchemas()Returns the metadata for all tables in the database.Schema
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()Executes the INSERT command, returning primary key values.Schema
isReadQuery()Returns a value indicating whether a SQL statement is for read purpose.Schema
quoteColumnName()Quotes a column name for use in a query.Schema
quoteSimpleColumnName()Quotes a simple column name for use in a query.Schema
quoteSimpleTableName()Quotes a simple table name for use in a query.Schema
quoteTableName()Quotes a table name for use in a query.Schema
quoteValue()Quotes a string value for use in a query.Schema
refresh()Refreshes the schema.Schema
refreshTableSchema()Refreshes the particular table schema.Schema
releaseSavepoint()Releases an existing savepoint.Schema
resolveRawTableName()Resolves the table name and schema name (if any) without loading database metadata.Schema
rollBackSavepoint()Rolls back to a previously created savepoint.Schema
setTransactionIsolationLevel()Sets the isolation level of the current transaction.Schema
supportsSavepoint()Schema
unquoteSimpleColumnName()Unquotes a simple column name.Schema
unquoteSimpleTableName()Unquotes a simple table name.Schema
createColumnSchema() protectedCreates a column schema for the database.Schema
findSchemaNames() protectedReturns all schema names in the database, including the default one but not system schemas.Schema
findTableNames() protectedReturns all table names in the database.Schema
getCacheKey() protectedReturns the cache key for the specified table name.Schema
getCacheTag() protectedReturns the cache tag name.Schema
getColumnPhpType() protectedExtracts the PHP type from abstract DB type.Schema
getSchemaMetadata() protectedReturns the metadata of the given type for all tables in the given schema.Schema
getTableMetadata() protectedReturns the metadata of the given type for the given table.Schema
getTableNameParts() protectedSplits full table name into parts.Schema
loadTableSchema() protected abstractLoads the metadata for the specified table.Schema
normalizePdoRowKeyCase() protectedChanges row’s array key case to lower if PDO’s one is set to uppercase.Schema
resolveTableName() protectedResolves the table name and schema name (if any).Schema
setTableMetadata() protectedSets the metadata of the given type for the given table.Schema
ConstantValueDescriptionDefined by
TYPE_PK'pk'Schema
TYPE_UPK'upk'Schema
TYPE_BIGPK'bigpk'Schema
TYPE_UBIGPK'ubigpk'Schema
TYPE_CHAR'char'Schema
TYPE_STRING'string'Schema
TYPE_TEXT'text'Schema
TYPE_TINYINT'tinyint'Schema
TYPE_SMALLINT'smallint'Schema
TYPE_INTEGER'integer'Schema
TYPE_BIGINT'bigint'Schema
TYPE_FLOAT'float'Schema
TYPE_DOUBLE'double'Schema
TYPE_DECIMAL'decimal'Schema
TYPE_DATETIME'datetime'Schema
TYPE_TIMESTAMP'timestamp'Schema
TYPE_TIME'time'Schema
TYPE_DATE'date'Schema
TYPE_BINARY'binary'Schema
TYPE_BOOLEAN'boolean'Schema
TYPE_MONEY'money'Schema
TYPE_JSON'json'Schema
SCHEMA_CACHE_VERSION1Schema cache version, to detect incompatibilities in cached values when the data format of the cache changes.Schema
public list<string> $systemSchemaNames = []

List of schema names that should be excluded from getSchemaNames().

DBMS-specific implementations may use this list in findSchemaNames().

public yii\db\TableSchema[] $tableSchemas

The metadata for all tables in the database.

Each array element is an instance of TableSchema or its child class.

Access

Read-only (virtual property).

public string $transactionIsolationLevel

The transaction isolation level to use for this transaction.

This can be one of Transaction::READ_UNCOMMITTED, Transaction::READ_COMMITTED, Transaction::REPEATABLE_READ and Transaction::SERIALIZABLE but also a string containing DBMS specific syntax to be used after SET TRANSACTION ISOLATION LEVEL.

Access

Write-only (virtual property).

protected string|string[] $columnQuoteCharacter = '"'

Character used to quote column names.

An array of 2 characters can be used in case starting and ending characters are different.

Since

2.0.14

protected string|string[] $tableQuoteCharacter = "'"

Character used to quote schema, table, etc. names.

An array of 2 characters can be used in case starting and ending characters are different.

Since

2.0.14

public function convertException(Exception $e, string $rawSql): yii\db\Exception

Converts a DB exception to a more concrete one if possible.

Parameters

ParameterTypeDescription
$eException
$rawSqlstringSQL that produced exception

Returns

Exception

public function createColumnSchemaBuilder(string $type, int|string|array|null $length = null): yii\db\ColumnSchemaBuilder

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.

Parameters

ParameterTypeDescription
$typestringType of the column. See ColumnSchemaBuilder::$type.
$lengthint|string|array|nullLength or precision of the column. See ColumnSchemaBuilder::$length.

Returns

ColumnSchemaBuilder: Column schema builder instance

Since

2.0.6

public function createQueryBuilder(): yii\db\TQueryBuilder

Creates a query builder for the database.

This method may be overridden by child classes to create a DBMS-specific query builder.

Returns

yii\db\TQueryBuilder: Query builder instance

public function createSavepoint(string $name): mixed

Creates a new savepoint.

Parameters

ParameterTypeDescription
$namestringThe savepoint name

Returns

mixed

public function findUniqueIndexes(yii\db\TableSchema $table): array

Returns all unique indexes for the given table.

Each array element is of the following structure:

[
'IndexName1' => ['col1' [, ...]],
'IndexName2' => ['col2' [, ...]],
]

This method should be overridden by child classes in order to support this feature because the default implementation simply throws an exception

Parameters

ParameterTypeDescription
$tableTableSchemaThe table metadata

Returns

array: All unique indexes for the given table.

Throws

public function getLastInsertID(string $sequenceName = ''): string

Returns the ID of the last inserted row or sequence value.

Parameters

ParameterTypeDescription
$sequenceNamestringName of the sequence object (required by some DBMS)

Returns

string: The row ID of the last row inserted, or the last value retrieved from the sequence object

Throws

See also

public function getPdoType(mixed $data): int

Determines the PDO type for the given PHP data value.

Parameters

ParameterTypeDescription
$datamixedThe data whose PDO type is to be determined

Returns

int: The PDO type

See also

public function getQueryBuilder(): yii\db\TQueryBuilder

Returns

yii\db\TQueryBuilder: The query builder for this connection.

public function getRawTableName(string $name): string

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 Connection::$tablePrefix.

Parameters

ParameterTypeDescription
$namestringThe table name to be converted

Returns

string: The real name of the given table name

public function getSchemaNames(bool $refresh = false): string[]

Returns all schema names in the database, except system schemas.

Parameters

ParameterTypeDescription
$refreshboolWhether to fetch the latest available schema names. If this is false, schema names fetched previously (if available) will be returned.

Returns

string[]: All schema names in the database, except system schemas.

Since

2.0.4

public function getServerVersion(): string

Returns a server version as a string comparable by version_compare().

Returns

string: Server version as a string.

Since

2.0.14

public function getTableNames(string $schema = '', bool $refresh = false): string[]

Returns all table names in the database.

Parameters

ParameterTypeDescription
$schemastringThe 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.
$refreshboolWhether to fetch the latest available table names. If this is false, table names fetched previously (if available) will be returned.

Returns

string[]: All table names in the database.

public function getTableSchema(string $name, bool $refresh = false): yii\db\TableSchema|null

Obtains the metadata for the named table.

Parameters

ParameterTypeDescription
$namestringTable name. The table name may contain schema name if any. Do not quote the table name.
$refreshboolWhether to reload the table schema even if it is found in the cache.

Returns

TableSchema|null: Table metadata. null if the named table does not exist.

public function getTableSchemas(string $schema = '', bool $refresh = false): yii\db\TableSchema[]

Returns the metadata for all tables in the database.

Parameters

ParameterTypeDescription
$schemastringThe schema of the tables. Defaults to empty string, meaning the current or default schema name.
$refreshboolWhether to fetch the latest available table schemas. If this is false, cached data may be returned if available.

Returns

TableSchema[]: The metadata for all tables in the database. Each array element is an instance of TableSchema or its child class.

public function insert(string $table, array $columns): array|false

Executes the INSERT command, returning primary key values.

Parameters

ParameterTypeDescription
$tablestringThe table that new rows will be inserted into.
$columnsarrayThe column data (name => value) to be inserted into the table.

Returns

array|false: Primary key values or false if the command fails

Since

2.0.4

public function isReadQuery(string $sql): bool

Returns a value indicating whether a SQL statement is for read purpose.

Parameters

ParameterTypeDescription
$sqlstringThe SQL statement

Returns

bool: Whether a SQL statement is for read purpose.

public function quoteColumnName(string $name): string

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.

Parameters

ParameterTypeDescription
$namestringColumn name.

Returns

string: The properly quoted column name.

See also

public function quoteSimpleColumnName(string $name): string

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.

Parameters

ParameterTypeDescription
$namestringColumn name.

Returns

string: The properly quoted column name.

public function quoteSimpleTableName(string $name): string

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.

Parameters

ParameterTypeDescription
$namestringTable name.

Returns

string: The properly quoted table name.

public function quoteTableName(string $name): string

Quotes a table name for use in a query.

If the table name contains schema prefix, the prefix will also be properly quoted. If the table name is already fully enclosed in the quote characters, or contains ’(’ or ’{{’, then this method will do nothing.

Parameters

ParameterTypeDescription
$namestringTable name.

Returns

string: The properly quoted table name.

See also

public function quoteValue(mixed $str): mixed

Quotes a string value for use in a query.

Note that if the parameter is not a string, it will be returned without change.

Parameters

ParameterTypeDescription
$strmixedString to be quoted. If the parameter is not a string, it will be returned without change.

Returns

mixed: The properly quoted string, or the original data if it is not a string.

See also

public function refresh(): mixed

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.

Returns

mixed

public function refreshTableSchema(string $name): mixed

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.

Parameters

ParameterTypeDescription
$namestringTable name.

Returns

mixed

Since

2.0.6

public function releaseSavepoint(string $name): mixed

Releases an existing savepoint.

Parameters

ParameterTypeDescription
$namestringThe savepoint name

Returns

mixed

public function resolveRawTableName(string $name): yii\db\TableSchema

Resolves the table name and schema name (if any) without loading database metadata.

Parameters

ParameterTypeDescription
$namestringThe table name.

Returns

TableSchema: TableSchema with resolved table, schema, etc. names.

Throws

Since

22.0

public function rollBackSavepoint(string $name): mixed

Rolls back to a previously created savepoint.

Parameters

ParameterTypeDescription
$namestringThe savepoint name

Returns

mixed

public function setTransactionIsolationLevel(string $level): mixed

Sets the isolation level of the current transaction.

Parameters

ParameterTypeDescription
$levelstringThe transaction isolation level to use for this transaction. This can be one of Transaction::READ_UNCOMMITTED, Transaction::READ_COMMITTED, Transaction::REPEATABLE_READ and Transaction::SERIALIZABLE but also a string containing DBMS specific syntax to be used after SET TRANSACTION ISOLATION LEVEL.

Returns

mixed

See also

public function supportsSavepoint(): bool

Returns

bool: Whether this DBMS supports savepoint.

public function unquoteSimpleColumnName(string $name): string

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.

Parameters

ParameterTypeDescription
$namestringColumn name.

Returns

string: Unquoted column name.

Since

2.0.14

public function unquoteSimpleTableName(string $name): string

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.

Parameters

ParameterTypeDescription
$namestringTable name.

Returns

string: Unquoted table name.

Since

2.0.14

protected function createColumnSchema(): yii\db\T

Creates a column schema for the database.

This method may be overridden by child classes to create a DBMS-specific column schema.

Returns

yii\db\T: Column schema instance.

Throws

protected function findSchemaNames(): array

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.

Returns

array: All schema names in the database, except system schemas.

Throws

Since

2.0.4

protected function findTableNames(string $schema = ''): array

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.

Parameters

ParameterTypeDescription
$schemastringThe schema of the tables. Defaults to empty string, meaning the current or default schema.

Returns

array: All table names in the database. The names have NO schema name prefix.

Throws

protected function getCacheKey(string $name): mixed

Returns the cache key for the specified table name.

Parameters

ParameterTypeDescription
$namestringThe table name.

Returns

mixed: The cache key.

protected function getCacheTag(): string

Returns the cache tag name.

This allows refresh() to invalidate all cached table schemas.

Returns

string: The cache tag name

protected function getColumnPhpType(yii\db\ColumnSchema $column): string

Extracts the PHP type from abstract DB type.

Parameters

ParameterTypeDescription
$columnColumnSchemaThe column schema information

Returns

string: PHP type name

protected function getSchemaMetadata(string $schema, string $type, bool $refresh): array

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.

Parameters

ParameterTypeDescription
$schemastringThe schema of the metadata. Defaults to empty string, meaning the current or default schema name.
$typestringMetadata type.
$refreshboolWhether to fetch the latest available table metadata. If this is false, cached data may be returned if available.

Returns

array: Array of metadata.

Since

2.0.13

protected function getTableMetadata(string $name, string $type, bool $refresh): mixed

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.

Parameters

ParameterTypeDescription
$namestringTable name. The table name may contain schema name if any. Do not quote the table name.
$typestringMetadata type.
$refreshboolWhether to reload the table metadata even if it is found in the cache.

Returns

mixed: Metadata.

Since

2.0.13

protected function getTableNameParts(string $name): array

Splits full table name into parts.

Parameters

ParameterTypeDescription
$namestringFull table name.

Returns

array: Table name parts.

Since

2.0.22

abstract protected function loadTableSchema(string $name): yii\db\TableSchema|null

Loads the metadata for the specified table.

Parameters

ParameterTypeDescription
$namestringTable name

Returns

TableSchema|null: DBMS-dependent table metadata, null if the table does not exist.

protected function normalizePdoRowKeyCase(array $row, bool $multiple): array

Changes row’s array key case to lower if PDO’s one is set to uppercase.

Parameters

ParameterTypeDescription
$rowarrayRow’s array or an array of row’s arrays.
$multipleboolWhether multiple rows or a single row passed.

Returns

array: Normalized row or rows.

Since

2.0.13

protected function resolveTableName(string $name): yii\db\TableSchema

Resolves the table name and schema name (if any).

Parameters

ParameterTypeDescription
$namestringThe table name

Returns

TableSchema: TableSchema with resolved table, schema, etc. names.

Throws

Since

2.0.13

protected function setTableMetadata(string $name, string $type, mixed $data): mixed

Sets the metadata of the given type for the given table.

Parameters

ParameterTypeDescription
$namestringTable name.
$typestringMetadata type.
$datamixedMetadata.

Returns

mixed

Since

2.0.13