Schema is the class for retrieving metadata from MS SQL Server databases (version 2008 and above).
Defined in: yii\base\BaseObject::__call()
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 function __call($name, $params)
{
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
$config
.If this method is overridden in a child class, it is recommended that
$config
here.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\base\BaseObject::__get()
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 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);
}
public boolean __isset ( $name ) $name string
The property name or the event name
return booleanWhether 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\base\BaseObject::__set()
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 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\base\BaseObject::__unset()
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.
See also https://www.php.net/manual/en/function.unset.php.
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\base\BaseObject::canGetProperty()
Returns a value indicating whether a property can be read.
A property is readable if:
$checkVars
is true);See also canSetProperty().
public function canGetProperty($name, $checkVars = true)
{
return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}
Defined in: yii\base\BaseObject::canSetProperty()
Returns a value indicating whether a property can be set.
A property is writable if:
$checkVars
is true);See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
return booleanWhether the property can be written
public function canSetProperty($name, $checkVars = true)
{
return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}
Deprecated since 2.0.14. On PHP >=5.5, use ::class
instead.
public static function className()
{
return get_called_class();
}
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\db\Schema::createColumnSchema()
Creates a column schema for the database.
This method may be overridden by child classes to create a DBMS-specific column schema.
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 function createColumnSchemaBuilder($type, $length = null)
{
return Yii::createObject(ColumnSchemaBuilder::className(), [$type, $length, $this->db]);
}
Creates a query builder for the MSSQL database.
public function createQueryBuilder()
{
return Yii::createObject(QueryBuilder::className(), [$this->db]);
}
Creates a new savepoint.
public function createSavepoint($name)
{
$this->db->createCommand("SAVE TRANSACTION $name")->execute();
}
Collects the metadata of table columns.
protected function findColumns($table)
{
$columnsTableName = 'INFORMATION_SCHEMA.COLUMNS';
$whereSql = '[t1].[table_name] = ' . $this->db->quoteValue($table->name);
if ($table->catalogName !== null) {
$columnsTableName = "{$table->catalogName}.{$columnsTableName}";
$whereSql .= " AND [t1].[table_catalog] = '{$table->catalogName}'";
}
if ($table->schemaName !== null) {
$whereSql .= " AND [t1].[table_schema] = '{$table->schemaName}'";
}
$columnsTableName = $this->quoteTableName($columnsTableName);
$sql = <<<SQL
CT
].[column_name],
].[is_nullable],
E WHEN [t1].[data_type] IN ('char','varchar','nchar','nvarchar','binary','varbinary') THEN
CASE WHEN [t1].[character_maximum_length] = NULL OR [t1].[character_maximum_length] = -1 THEN
[t1].[data_type]
ELSE
[t1].[data_type] + '(' + LTRIM(RTRIM(CONVERT(CHAR,[t1].[character_maximum_length]))) + ')'
END
E
[t1].[data_type]
AS 'data_type',
].[column_default],
UMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsIdentity') AS is_identity,
UMNPROPERTY(OBJECT_ID([t1].[table_schema] + '.' + [t1].[table_name]), [t1].[column_name], 'IsComputed') AS is_computed,
SELECT CONVERT(VARCHAR, [t2].[value])
OM [sys].[extended_properties] AS [t2]
ERE
t2].[class] = 1 AND
t2].[class_desc] = 'OBJECT_OR_COLUMN' AND
t2].[name] = 'MS_Description' AND
t2].[major_id] = OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[table_name]) AND
t2].[minor_id] = COLUMNPROPERTY(OBJECT_ID([t1].[TABLE_SCHEMA] + '.' + [t1].[TABLE_NAME]), [t1].[COLUMN_NAME], 'ColumnID')
s comment
{$columnsTableName} AS [t1]
E {$whereSql}
try {
$columns = $this->db->createCommand($sql)->queryAll();
if (empty($columns)) {
return false;
}
} catch (\Exception $e) {
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 = '';
}
$table->columns[$column->name] = $column;
}
return true;
}
Collects the foreign key column details for the given table.
protected function findForeignKeys($table)
{
$object = $table->name;
if ($table->schemaName !== null) {
$object = $table->schemaName . '.' . $object;
}
if ($table->catalogName !== null) {
$object = $table->catalogName . '.' . $object;
}
$sql = <<<'SQL'
CT
].[name] AS [fk_name],
].[name] AS [fk_column_name],
ECT_NAME([fk].[referenced_object_id]) AS [uq_table_name],
].[name] AS [uq_column_name]
s].[foreign_keys] AS [fk]
ER JOIN [sys].[foreign_key_columns] AS [fkc] ON
k].[object_id] = [fkc].[constraint_object_id]
ER JOIN [sys].[columns] AS [cp] ON
k].[parent_object_id] = [cp].[object_id] AND
kc].[parent_column_id] = [cp].[column_id]
ER JOIN [sys].[columns] AS [cr] ON
k].[referenced_object_id] = [cr].[object_id] AND
kc].[referenced_column_id] = [cr].[column_id]
E
].[parent_object_id] = OBJECT_ID(:object)
$rows = $this->db->createCommand($sql, [
':object' => $object,
])->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 function findPrimaryKeys($table)
{
$result = [];
foreach ($this->findTableConstraints($table, 'PRIMARY KEY') as $row) {
$result[] = $row['field_name'];
}
$table->primaryKey = $result;
}
protected function findSchemaNames()
{
static $sql = <<<'SQL'
CT [s].[name]
[sys].[schemas] AS [s]
R JOIN [sys].[database_principals] AS [p] ON [p].[principal_id] = [s].[principal_id]
E [p].[is_fixed_role] = 0 AND [p].[sid] IS NOT NULL
R BY [s].[name] ASC
return $this->db->createCommand($sql)->queryColumn();
}
Collects the constraint details for the given table and constraint type.
protected function findTableConstraints($table, $type)
{
$keyColumnUsageTableName = 'INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
$tableConstraintsTableName = 'INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
if ($table->catalogName !== null) {
$keyColumnUsageTableName = $table->catalogName . '.' . $keyColumnUsageTableName;
$tableConstraintsTableName = $table->catalogName . '.' . $tableConstraintsTableName;
}
$keyColumnUsageTableName = $this->quoteTableName($keyColumnUsageTableName);
$tableConstraintsTableName = $this->quoteTableName($tableConstraintsTableName);
$sql = <<<SQL
CT
[kcu].[constraint_name] AS [index_name],
[kcu].[column_name] AS [field_name]
{$keyColumnUsageTableName} AS [kcu]
JOIN {$tableConstraintsTableName} AS [tc] ON
[kcu].[table_schema] = [tc].[table_schema] AND
[kcu].[table_name] = [tc].[table_name] AND
[kcu].[constraint_name] = [tc].[constraint_name]
E
[tc].[constraint_type] = :type AND
[kcu].[table_name] = :tableName AND
[kcu].[table_schema] = :schemaName
return $this->db
->createCommand($sql, [
':tableName' => $table->name,
':schemaName' => $table->schemaName,
':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 ( $schema = '' ) $schema stringThe schema of the tables. Defaults to empty string, meaning the current or default schema.
return arrayAll table names in the database. The names have NO schema name prefix.
throws yii\base\NotSupportedExceptionif this method is not supported by the DBMS.
protected function findTableNames($schema = '')
{
if ($schema === '') {
$schema = $this->defaultSchema;
}
$sql = <<<'SQL'
CT [t].[table_name]
[INFORMATION_SCHEMA].[TABLES] AS [t]
E [t].[table_schema] = :schema AND [t].[table_type] IN ('BASE TABLE', 'VIEW')
R BY [t].[table_name]
return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
}
Returns all unique indexes for the given table.
Each array element is of the following structure:
[
'IndexName1' => ['col1' [, ...]],
'IndexName2' => ['col2' [, ...]],
]
public function findUniqueIndexes($table)
{
$result = [];
foreach ($this->findTableConstraints($table, 'UNIQUE') as $row) {
$result[$row['index_name']][] = $row['field_name'];
}
return $result;
}
protected function findViewNames($schema = '')
{
if ($schema === '') {
$schema = $this->defaultSchema;
}
$sql = <<<'SQL'
CT [t].[table_name]
[INFORMATION_SCHEMA].[TABLES] AS [t]
E [t].[table_schema] = :schema AND [t].[table_type] = 'VIEW'
R BY [t].[table_name]
return $this->db->createCommand($sql, [':schema' => $schema])->queryColumn();
}
protected mixed getCacheKey ( $name ) $name string
The table name.
return mixedThe cache key.
protected function getCacheKey($name)
{
return [
__CLASS__,
$this->db->dsn,
$this->db->username,
$this->getRawTableName($name),
];
}
protected function getCacheTag()
{
return md5(serialize([
__CLASS__,
$this->db->dsn,
$this->db->username,
]));
}
protected function getColumnPhpType($column)
{
static $typeMap = [
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';
}
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.');
}
public function getPdoType($data)
{
static $typeMap = [
'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;
}
public function getQueryBuilder()
{
if ($this->_builder === null) {
$this->_builder = $this->createQueryBuilder();
}
return $this->_builder;
}
public function getRawTableName($name)
{
if (strpos($name, '{{') !== false) {
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
return str_replace('%', $this->db->tablePrefix, $name);
}
return $name;
}
public \yii\db\CheckConstraint[][] getSchemaChecks ( $schema = '', $refresh = false ) $schema string
The schema of the tables. Defaults to empty string, meaning the current or default schema name.
$refresh booleanWhether to fetch the latest available table schemas. If this is false, cached data may be returned if available.
return \yii\db\CheckConstraint[][]Check constraints for all tables in the database. Each array element is an array of yii\db\CheckConstraint or its child classes.
public function getSchemaChecks($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'checks', $refresh);
}
public function getSchemaDefaultValues($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'defaultValues', $refresh);
}
public \yii\db\ForeignKeyConstraint[][] getSchemaForeignKeys ( $schema = '', $refresh = false ) $schema string
The schema of the tables. Defaults to empty string, meaning the current or default schema name.
$refresh booleanWhether to fetch the latest available table schemas. If this is false, cached data may be returned if available.
return \yii\db\ForeignKeyConstraint[][]Foreign keys for all tables in the database. Each array element is an array of yii\db\ForeignKeyConstraint or its child classes.
public function getSchemaForeignKeys($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'foreignKeys', $refresh);
}
public \yii\db\IndexConstraint[][] getSchemaIndexes ( $schema = '', $refresh = false ) $schema string
The schema of the tables. Defaults to empty string, meaning the current or default schema name.
$refresh booleanWhether to fetch the latest available table schemas. If this is false, cached data may be returned if available.
return \yii\db\IndexConstraint[][]Indexes for all tables in the database. Each array element is an array of yii\db\IndexConstraint or its child classes.
public function getSchemaIndexes($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'indexes', $refresh);
}
public string[] getSchemaNames ( $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;
}
public yii\db\Constraint[] getSchemaPrimaryKeys ( $schema = '', $refresh = false ) $schema string
The schema of the tables. Defaults to empty string, meaning the current or default schema name.
$refresh booleanWhether to fetch the latest available table schemas. If this is false
, cached data may be returned if available.
Primary keys for all tables in the database. Each array element is an instance of yii\db\Constraint or its child class.
public function getSchemaPrimaryKeys($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'primaryKey', $refresh);
}
public \yii\db\Constraint[][] getSchemaUniques ( $schema = '', $refresh = false ) $schema string
The schema of the tables. Defaults to empty string, meaning the current or default schema name.
$refresh booleanWhether to fetch the latest available table schemas. If this is false, cached data may be returned if available.
return \yii\db\Constraint[][]Unique constraints for all tables in the database. Each array element is an array of yii\db\Constraint or its child classes.
public function getSchemaUniques($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'uniques', $refresh);
}
public function getServerVersion()
{
if ($this->_serverVersion === null) {
$this->_serverVersion = $this->db->getSlavePdo(true)->getAttribute(\PDO::ATTR_SERVER_VERSION);
}
return $this->_serverVersion;
}
public function getTableChecks($name, $refresh = false)
{
return $this->getTableMetadata($name, 'checks', $refresh);
}
public function getTableDefaultValues($name, $refresh = false)
{
return $this->getTableMetadata($name, 'defaultValues', $refresh);
}
public function getTableForeignKeys($name, $refresh = false)
{
return $this->getTableMetadata($name, 'foreignKeys', $refresh);
}
public function getTableIndexes($name, $refresh = false)
{
return $this->getTableMetadata($name, 'indexes', $refresh);
}
Splits full table name into parts
protected function getTableNameParts($name)
{
$parts = [$name];
preg_match_all('/([^.\[\]]+)|\[([^\[\]]+)\]/', $name, $matches);
if (isset($matches[0]) && is_array($matches[0]) && !empty($matches[0])) {
$parts = $matches[0];
}
$parts = str_replace(['[', ']'], '', $parts);
return $parts;
}
public string[] getTableNames ( $schema = '', $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 booleanWhether 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];
}
public function getTablePrimaryKey($name, $refresh = false)
{
return $this->getTableMetadata($name, 'primaryKey', $refresh);
}
public function getTableSchema($name, $refresh = false)
{
return $this->getTableMetadata($name, 'schema', $refresh);
}
public yii\db\TableSchema[] getTableSchemas ( $schema = '', $refresh = false ) $schema string
The schema of the tables. Defaults to empty string, meaning the current or default schema name.
$refresh booleanWhether to fetch the latest available table schemas. If this is false
, cached data may be returned if available.
The metadata for all tables in the database. Each array element is an instance of yii\db\TableSchema or its child class.
public function getTableSchemas($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'schema', $refresh);
}
public function getTableUniques($name, $refresh = false)
{
return $this->getTableMetadata($name, 'uniques', $refresh);
}
public string[] getViewNames ( $schema = '', $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 booleanWhether 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\base\BaseObject::hasMethod()
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 function hasMethod($name)
{
return method_exists($this, $name);
}
Defined in: yii\base\BaseObject::hasProperty()
Returns a value indicating whether a property is defined.
A property is defined if:
$checkVars
is true);See also:
public boolean hasProperty ( $name, $checkVars = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
return booleanWhether the property is defined
public function hasProperty($name, $checkVars = true)
{
return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}
Defined in: yii\base\BaseObject::init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public function init()
{
}
Retrieving inserted data from a primary key request of type uniqueidentifier (for SQL Server 2005 or later) {@inheritdoc}
public void insert ( $table, $columns ) $table $columns public function insert($table, $columns)
{
$command = $this->db->createCommand()->insert($table, $columns);
if (!$command->execute()) {
return false;
}
$isVersion2005orLater = version_compare($this->db->getSchema()->getServerVersion(), '9', '>=');
$inserted = $isVersion2005orLater ? $command->pdoStatement->fetch() : [];
$tableSchema = $this->getTableSchema($table);
$result = [];
foreach ($tableSchema->primaryKey as $name) {
if (isset($inserted[$name])) {
$result[$name] = $inserted[$name];
} elseif ($tableSchema->columns[$name]->autoIncrement) {
$result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
} elseif (isset($columns[$name])) {
$result[$name] = $columns[$name];
} else {
$result[$name] = $tableSchema->columns[$name]->defaultValue;
}
}
return $result;
}
public function isReadQuery($sql)
{
$pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
return preg_match($pattern, $sql) > 0;
}
Loads the column information into a yii\db\mssql\ColumnSchema object.
protected function loadColumnSchema($info)
{
$isVersion2017orLater = version_compare($this->db->getSchema()->getServerVersion(), '14', '>=');
$column = $this->createColumnSchema();
$column->name = $info['column_name'];
$column->allowNull = $info['is_nullable'] === 'YES';
$column->dbType = $info['data_type'];
$column->enumValues = [];
$column->isPrimaryKey = null;
$column->autoIncrement = $info['is_identity'] == 1;
$column->isComputed = (bool)$info['is_computed'];
$column->unsigned = stripos($column->dbType, 'unsigned') !== false;
$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 ($isVersion2017orLater && $type === 'bit') {
$column->type = 'boolean';
}
if (!empty($matches[2])) {
$values = explode(',', $matches[2]);
$column->size = $column->precision = (int) $values[0];
if (isset($values[1])) {
$column->scale = (int) $values[1];
}
if ($isVersion2017orLater === false) {
if ($column->size === 1 && ($type === 'tinyint' || $type === 'bit')) {
$column->type = 'boolean';
} elseif ($type === 'bit') {
if ($column->size > 32) {
$column->type = 'bigint';
} elseif ($column->size === 32) {
$column->type = 'integer';
}
}
}
}
}
$column->phpType = $this->getColumnPhpType($column);
if ($info['column_default'] === '(NULL)') {
$info['column_default'] = null;
}
if (!$column->isPrimaryKey && ($column->type !== 'timestamp' || $info['column_default'] !== 'CURRENT_TIMESTAMP')) {
$column->defaultValue = $column->defaultPhpTypecast($info['column_default']);
}
return $column;
}
protected function loadTableChecks($tableName)
{
return $this->loadTableConstraints($tableName, 'checks');
}
protected function loadTableDefaultValues($tableName)
{
return $this->loadTableConstraints($tableName, 'defaults');
}
protected function loadTableForeignKeys($tableName)
{
return $this->loadTableConstraints($tableName, 'foreignKeys');
}
protected function loadTableIndexes($tableName)
{
static $sql = <<<'SQL'
CT
[i].[name] AS [name],
[iccol].[name] AS [column_name],
[i].[is_unique] AS [index_is_unique],
[i].[is_primary_key] AS [index_is_primary]
[sys].[indexes] AS [i]
R JOIN [sys].[index_columns] AS [ic]
ON [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id]
R JOIN [sys].[columns] AS [iccol]
ON [iccol].[object_id] = [ic].[object_id] AND [iccol].[column_id] = [ic].[column_id]
E [i].[object_id] = OBJECT_ID(:fullName)
R BY [ic].[key_ordinal] ASC
$resolvedName = $this->resolveTableName($tableName);
$indexes = $this->db->createCommand($sql, [
':fullName' => $resolvedName->fullName,
])->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 function loadTablePrimaryKey($tableName)
{
return $this->loadTableConstraints($tableName, 'primaryKey');
}
Loads the metadata for the specified table.
protected function loadTableSchema($name)
{
$table = new TableSchema();
$this->resolveTableNames($table, $name);
$this->findPrimaryKeys($table);
if ($this->findColumns($table)) {
$this->findForeignKeys($table);
return $table;
}
return null;
}
protected function loadTableUniques($tableName)
{
return $this->loadTableConstraints($tableName, 'uniques');
}
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 quoted or contains '(', '[[' or '{{', then this method will do nothing.
public function quoteColumnName($name)
{
if (preg_match('/^\[.*\]$/', $name)) {
return $name;
}
return parent::quoteColumnName($name);
}
Defined in: yii\db\Schema::quoteSimpleColumnName()
Quotes a simple column name for use in a query.
A simple column name should contain the column name only without any prefix. If the column name is already quoted or is the asterisk character '*', this method will do nothing.
public function quoteSimpleColumnName($name)
{
if (is_string($this->columnQuoteCharacter)) {
$startingCharacter = $endingCharacter = $this->columnQuoteCharacter;
} else {
list($startingCharacter, $endingCharacter) = $this->columnQuoteCharacter;
}
return $name === '*' || strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name . $endingCharacter;
}
Defined in: yii\db\Schema::quoteSimpleTableName()
Quotes a simple table name for use in a query.
A simple table name should contain the table name only without any schema prefix. If the table name is already quoted, this method will do nothing.
public function quoteSimpleTableName($name)
{
if (is_string($this->tableQuoteCharacter)) {
$startingCharacter = $endingCharacter = $this->tableQuoteCharacter;
} else {
list($startingCharacter, $endingCharacter) = $this->tableQuoteCharacter;
}
return strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name . $endingCharacter;
}
Defined in: yii\db\Schema::quoteTableName()
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 quoted or contains '(' or '{{', then this method will do nothing.
See also quoteSimpleTableName().
public function quoteTableName($name)
{
if (strncmp($name, '(', 1) === 0 && strpos($name, ')') === strlen($name) - 1) {
return $name;
}
if (strpos($name, '{{') !== false) {
return $name;
}
if (strpos($name, '.') === false) {
return $this->quoteSimpleTableName($name);
}
$parts = $this->getTableNameParts($name);
foreach ($parts as $i => $part) {
$parts[$i] = $this->quoteSimpleTableName($part);
}
return implode('.', $parts);
}
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;
}
return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
}
Defined in: yii\db\Schema::refresh()
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 function refresh()
{
$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\db\Schema::refreshTableSchema()
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 function refreshTableSchema($name)
{
$rawName = $this->getRawTableName($name);
unset($this->_tableMetadata[$rawName]);
$this->_tableNames = [];
$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 function releaseSavepoint($name)
{
}
Resolves the table name and schema name (if any).
protected function resolveTableName($name)
{
$resolvedName = new TableSchema();
$parts = $this->getTableNameParts($name);
$partCount = count($parts);
if ($partCount === 4) {
$resolvedName->catalogName = $parts[1];
$resolvedName->schemaName = $parts[2];
$resolvedName->name = $parts[3];
$resolvedName->fullName = $resolvedName->catalogName . '.' . $resolvedName->schemaName . '.' . $resolvedName->name;
} elseif ($partCount === 3) {
$resolvedName->catalogName = $parts[0];
$resolvedName->schemaName = $parts[1];
$resolvedName->name = $parts[2];
$resolvedName->fullName = $resolvedName->catalogName . '.' . $resolvedName->schemaName . '.' . $resolvedName->name;
} elseif ($partCount === 2) {
$resolvedName->schemaName = $parts[0];
$resolvedName->name = $parts[1];
$resolvedName->fullName = ($resolvedName->schemaName !== $this->defaultSchema ? $resolvedName->schemaName . '.' : '') . $resolvedName->name;
} else {
$resolvedName->schemaName = $this->defaultSchema;
$resolvedName->fullName = $resolvedName->name = $parts[0];
}
return $resolvedName;
}
Resolves the table name and schema name (if any).
protected function resolveTableNames($table, $name)
{
$parts = $this->getTableNameParts($name);
$partCount = count($parts);
if ($partCount === 4) {
$table->catalogName = $parts[1];
$table->schemaName = $parts[2];
$table->name = $parts[3];
$table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
} elseif ($partCount === 3) {
$table->catalogName = $parts[0];
$table->schemaName = $parts[1];
$table->name = $parts[2];
$table->fullName = $table->catalogName . '.' . $table->schemaName . '.' . $table->name;
} elseif ($partCount === 2) {
$table->schemaName = $parts[0];
$table->name = $parts[1];
$table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
} else {
$table->schemaName = $this->defaultSchema;
$table->fullName = $table->name = $parts[0];
}
}
Rolls back to a previously created savepoint.
public function rollBackSavepoint($name)
{
$this->db->createCommand("ROLLBACK TRANSACTION $name")->execute();
}
public function setTransactionIsolationLevel($level)
{
$this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
}
public function supportsSavepoint()
{
return $this->db->enableSavepoint;
}
Defined in: yii\db\Schema::unquoteSimpleColumnName()
Unquotes a simple column name.
A simple column name should contain the column name only without any prefix. If the column name is not quoted or is the asterisk character '*', this method will do nothing.
public function unquoteSimpleColumnName($name)
{
if (is_string($this->columnQuoteCharacter)) {
$startingCharacter = $this->columnQuoteCharacter;
} else {
$startingCharacter = $this->columnQuoteCharacter[0];
}
return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1);
}
Defined in: yii\db\Schema::unquoteSimpleTableName()
Unquotes a simple table name.
A simple table name should contain the table name only without any schema prefix. If the table name is not quoted, this method will do nothing.
public function unquoteSimpleTableName($name)
{
if (is_string($this->tableQuoteCharacter)) {
$startingCharacter = $this->tableQuoteCharacter;
} else {
$startingCharacter = $this->tableQuoteCharacter[0];
}
return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1);
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4