system system.base system.caching system.caching.dependencies system.collections system.console system.db system.db.ar system.db.schema system.db.schema.cubrid system.db.schema.mssql system.db.schema.mysql system.db.schema.oci system.db.schema.pgsql system.db.schema.sqlite system.gii system.i18n system.i18n.gettext system.logging system.test system.utils system.validators system.web system.web.actions system.web.auth system.web.filters system.web.form system.web.helpers system.web.renderers system.web.services system.web.widgets system.web.widgets.captcha system.web.widgets.pagers zii.behaviors zii.widgets zii.widgets.grid zii.widgets.jui

CMysqlSchema

system.db.schema.mysql
继承 class CMysqlSchema » CDbSchema » CComponent
可用自 1.0
源码 framework/db/schema/mysql/CMysqlSchema.php
CMysqlSchema is the class for retrieving metadata information from a MySQL database (version 4.1.x and 5.x).

公共属性

隐藏继承的属性

属性类型描述被定义在
columnTypes array the abstract column types mapped to physical column types. CMysqlSchema
commandBuilder CDbCommandBuilder the SQL command builder for this connection. CDbSchema
dbConnection CDbConnection database connection. CDbSchema
tableNames array Returns all table names in the database. CDbSchema
tables array Returns the metadata for all tables in the database. CDbSchema

受保护的属性

隐藏继承的属性

属性类型描述被定义在
serverVersion float server version. CMysqlSchema

公共方法

隐藏继承的方法

方法描述被定义在
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CDbSchema
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
addColumn() Builds a SQL statement for adding a new DB column. CDbSchema
addForeignKey() Builds a SQL statement for adding a foreign key constraint to an existing table. CDbSchema
addPrimaryKey() Builds a SQL statement for adding a primary key constraint to a table. CMysqlSchema
alterColumn() Builds a SQL statement for changing the definition of a column. CDbSchema
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
checkIntegrity() Enables or disables integrity check. CMysqlSchema
compareTableNames() Compares two table names. CMysqlSchema
createIndex() Builds a SQL statement for creating a new index. CDbSchema
createTable() Builds a SQL statement for creating a new DB table. CDbSchema
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
dropColumn() Builds a SQL statement for dropping a DB column. CDbSchema
dropForeignKey() Builds a SQL statement for dropping a foreign key constraint. CMysqlSchema
dropIndex() Builds a SQL statement for dropping an index. CDbSchema
dropPrimaryKey() Builds a SQL statement for removing a primary key constraint to an existing table. CMysqlSchema
dropTable() Builds a SQL statement for dropping a DB table. CDbSchema
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getColumnType() Converts an abstract column type into a physical column type. CDbSchema
getCommandBuilder() Returns the SQL command builder for this connection. CDbSchema
getDbConnection() Returns database connection. The connection is active. CDbSchema
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getTable() Obtains the metadata for the named table. CDbSchema
getTableNames() Returns all table names in the database. CDbSchema
getTables() Returns the metadata for all tables in the database. CDbSchema
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
quoteColumnName() Quotes a column name for use in a query. CDbSchema
quoteSimpleColumnName() Quotes a column name for use in a query. CMysqlSchema
quoteSimpleTableName() Quotes a table name for use in a query. CMysqlSchema
quoteTableName() Quotes a table name for use in a query. CDbSchema
raiseEvent() Raises an event. CComponent
refresh() Refreshes the schema. CDbSchema
renameColumn() Builds a SQL statement for renaming a column. CMysqlSchema
renameTable() Builds a SQL statement for renaming a DB table. CDbSchema
resetSequence() Resets the sequence value of a table's primary key. CMysqlSchema
truncateTable() Builds a SQL statement for truncating a DB table. CDbSchema

受保护的方法

隐藏继承的方法

方法描述被定义在
createColumn() Creates a table column. CMysqlSchema
createCommandBuilder() Creates a command builder for the database. CMysqlSchema
findColumns() Collects the table column metadata. CMysqlSchema
findConstraints() Collects the foreign key column details for the given table. CMysqlSchema
findTableNames() Returns all table names in the database. CMysqlSchema
getServerVersion() Returns server version. CMysqlSchema
loadTable() Loads the metadata for the specified table. CMysqlSchema
resolveTableNames() Generates various kinds of table names. CMysqlSchema

属性详情

columnTypes 属性 (自版本 v1.1.6 可用)
public array $columnTypes;

the abstract column types mapped to physical column types.

serverVersion 属性 只读
protected float getServerVersion()

server version.

方法详情

addPrimaryKey() 方法 (自版本 v1.1.14 可用)
public string addPrimaryKey(string $name, string $table, string|array $columns)
$name string not used in the MySQL syntax, the primary key is always called PRIMARY and is reserved.
$table string the table that the primary key constraint will be added to.
$columns string|array comma separated string or array of columns that the primary key will consist of.
{return} string the SQL statement for adding a primary key constraint to an existing table.
源码: framework/db/schema/mysql/CMysqlSchema.php#354 (显示)
public function addPrimaryKey($name,$table,$columns)
{
    if(
is_string($columns))
        
$columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
    foreach(
$columns as $i=>$col)
        
$columns[$i]=$this->quoteColumnName($col);
    return 
'ALTER TABLE ' $this->quoteTableName($table) . ' ADD PRIMARY KEY ('
        
implode(', '$columns). ' )';
}

Builds a SQL statement for adding a primary key constraint to a table.

checkIntegrity() 方法 (自版本 v1.1 可用)
public void checkIntegrity(boolean $check=true, string $schema='')
$check boolean whether to turn on or off the integrity check.
$schema string the schema of the tables. Defaults to empty string, meaning the current or default schema.
源码: framework/db/schema/mysql/CMysqlSchema.php#113 (显示)
public function checkIntegrity($check=true,$schema='')
{
    
$this->getDbConnection()->createCommand('SET FOREIGN_KEY_CHECKS='.($check?1:0))->execute();
}

Enables or disables integrity check.

compareTableNames() 方法
public boolean compareTableNames(string $name1, string $name2)
$name1 string table name 1
$name2 string table name 2
{return} boolean whether the two table names refer to the same table.
源码: framework/db/schema/mysql/CMysqlSchema.php#74 (显示)
public function compareTableNames($name1,$name2)
{
    return 
parent::compareTableNames(strtolower($name1),strtolower($name2));
}

Compares two table names. The table names can be either quoted or unquoted. This method will consider both cases.

createColumn() 方法
protected CDbColumnSchema createColumn(array $column)
$column array column metadata
{return} CDbColumnSchema normalized column metadata
源码: framework/db/schema/mysql/CMysqlSchema.php#198 (显示)
protected function createColumn($column)
{
    
$c=new CMysqlColumnSchema;
    
$c->name=$column['Field'];
    
$c->rawName=$this->quoteColumnName($c->name);
    
$c->allowNull=$column['Null']==='YES';
    
$c->isPrimaryKey=strpos($column['Key'],'PRI')!==false;
    
$c->isForeignKey=false;
    
$c->init($column['Type'],$column['Default']);
    
$c->autoIncrement=strpos(strtolower($column['Extra']),'auto_increment')!==false;
    if(isset(
$column['Comment']))
        
$c->comment=$column['Comment'];

    return 
$c;
}

Creates a table column.

createCommandBuilder() 方法 (自版本 v1.1.13 可用)
protected CDbCommandBuilder createCommandBuilder()
{return} CDbCommandBuilder command builder instance
源码: framework/db/schema/mysql/CMysqlSchema.php#274 (显示)
protected function createCommandBuilder()
{
    return new 
CMysqlCommandBuilder($this);
}

Creates a command builder for the database. This method overrides parent implementation in order to create a MySQL specific command builder

dropForeignKey() 方法 (自版本 v1.1.6 可用)
public string dropForeignKey(string $name, string $table)
$name string the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
$table string the table whose foreign is to be dropped. The name will be properly quoted by the method.
{return} string the SQL statement for dropping a foreign key constraint.
源码: framework/db/schema/mysql/CMysqlSchema.php#326 (显示)
public function dropForeignKey($name$table)
{
    return 
'ALTER TABLE '.$this->quoteTableName($table)
        .
' DROP FOREIGN KEY '.$this->quoteColumnName($name);
}

Builds a SQL statement for dropping a foreign key constraint.

dropPrimaryKey() 方法 (自版本 v1.1.13 可用)
public string dropPrimaryKey(string $name, string $table)
$name string the name of the primary key constraint to be removed.
$table string the table that the primary key constraint will be removed from.
{return} string the SQL statement for removing a primary key constraint from an existing table.
源码: framework/db/schema/mysql/CMysqlSchema.php#340 (显示)
public function dropPrimaryKey($name,$table)
{
    return 
'ALTER TABLE ' $this->quoteTableName($table) . ' DROP PRIMARY KEY';

}

Builds a SQL statement for removing a primary key constraint to an existing table.

findColumns() 方法
protected boolean findColumns(CMysqlTableSchema $table)
$table CMysqlTableSchema the table metadata
{return} boolean whether the table exists in the database
源码: framework/db/schema/mysql/CMysqlSchema.php#163 (显示)
protected function findColumns($table)
{
    
$sql='SHOW FULL COLUMNS FROM '.$table->rawName;
    try
    {
        
$columns=$this->getDbConnection()->createCommand($sql)->queryAll();
    }
    catch(
Exception $e)
    {
        return 
false;
    }
    foreach(
$columns as $column)
    {
        
$c=$this->createColumn($column);
        
$table->columns[$c->name]=$c;
        if(
$c->isPrimaryKey)
        {
            if(
$table->primaryKey===null)
                
$table->primaryKey=$c->name;
            elseif(
is_string($table->primaryKey))
                
$table->primaryKey=array($table->primaryKey,$c->name);
            else
                
$table->primaryKey[]=$c->name;
            if(
$c->autoIncrement)
                
$table->sequenceName='';
        }
    }
    return 
true;
}

Collects the table column metadata.

findConstraints() 方法
protected void findConstraints(CMysqlTableSchema $table)
$table CMysqlTableSchema the table metadata
源码: framework/db/schema/mysql/CMysqlSchema.php#229 (显示)
protected function findConstraints($table)
{
    
$row=$this->getDbConnection()->createCommand('SHOW CREATE TABLE '.$table->rawName)->queryRow();
    
$matches=array();
    
$regexp='/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
    foreach(
$row as $sql)
    {
        if(
preg_match_all($regexp,$sql,$matches,PREG_SET_ORDER))
            break;
    }
    foreach(
$matches as $match)
    {
        
$keys=array_map('trim',explode(',',str_replace(array('`','"'),'',$match[1])));
        
$fks=array_map('trim',explode(',',str_replace(array('`','"'),'',$match[3])));
        foreach(
$keys as $k=>$name)
        {
            
$table->foreignKeys[$name]=array(str_replace(array('`','"'),'',$match[2]),$fks[$k]);
            if(isset(
$table->columns[$name]))
                
$table->columns[$name]->isForeignKey=true;
        }
    }
}

Collects the foreign key column details for the given table.

findTableNames() 方法
protected array findTableNames(string $schema='')
$schema string the schema of the tables. Defaults to empty string, meaning the current or default schema. If not empty, the returned table names will be prefixed with the schema name.
{return} array all table names in the database.
源码: framework/db/schema/mysql/CMysqlSchema.php#258 (显示)
protected function findTableNames($schema='')
{
    if(
$schema==='')
        return 
$this->getDbConnection()->createCommand('SHOW TABLES')->queryColumn();
    
$names=$this->getDbConnection()->createCommand('SHOW TABLES FROM '.$this->quoteTableName($schema))->queryColumn();
    foreach(
$names as &$name)
        
$name=$schema.'.'.$name;
    return 
$names;
}

Returns all table names in the database.

getServerVersion() 方法
protected float getServerVersion()
{return} float server version.
源码: framework/db/schema/mysql/CMysqlSchema.php#217 (显示)
protected function getServerVersion()
{
    
$version=$this->getDbConnection()->getAttribute(PDO::ATTR_SERVER_VERSION);
    
$digits=array();
    
preg_match('/(\d+)\.(\d+)\.(\d+)/'$version$digits);
    return 
floatval($digits[1].'.'.$digits[2].$digits[3]);
}

loadTable() 方法
protected CMysqlTableSchema loadTable(string $name)
$name string table name
{return} CMysqlTableSchema driver dependent table metadata. Null if the table does not exist.
源码: framework/db/schema/mysql/CMysqlSchema.php#123 (显示)
protected function loadTable($name)
{
    
$table=new CMysqlTableSchema;
    
$this->resolveTableNames($table,$name);

    if(
$this->findColumns($table))
    {
        
$this->findConstraints($table);
        return 
$table;
    }
    else
        return 
null;
}

Loads the metadata for the specified table.

quoteSimpleColumnName() 方法 (自版本 v1.1.6 可用)
public string quoteSimpleColumnName(string $name)
$name string column name
{return} string the properly quoted column name
源码: framework/db/schema/mysql/CMysqlSchema.php#61 (显示)
public function quoteSimpleColumnName($name)
{
    return 
'`'.$name.'`';
}

Quotes a column name for use in a query. A simple column name does not contain prefix.

quoteSimpleTableName() 方法 (自版本 v1.1.6 可用)
public string quoteSimpleTableName(string $name)
$name string table name
{return} string the properly quoted table name
源码: framework/db/schema/mysql/CMysqlSchema.php#49 (显示)
public function quoteSimpleTableName($name)
{
    return 
'`'.$name.'`';
}

Quotes a table name for use in a query. A simple table name does not schema prefix.

renameColumn() 方法 (自版本 v1.1.6 可用)
public string renameColumn(string $table, string $name, string $newName)
$table string the table whose column is to be renamed. The name will be properly quoted by the method.
$name string the old name of the column. The name will be properly quoted by the method.
$newName string the new name of the column. The name will be properly quoted by the method.
{return} string the SQL statement for renaming a DB column.
源码: framework/db/schema/mysql/CMysqlSchema.php#288 (显示)
public function renameColumn($table$name$newName)
{
    
$db=$this->getDbConnection();
    
$row=$db->createCommand('SHOW CREATE TABLE '.$db->quoteTableName($table))->queryRow();
    if(
$row===false)
        throw new 
CDbException(Yii::t('yii','Unable to find "{column}" in table "{table}".',array('{column}'=>$name,'{table}'=>$table)));
    if(isset(
$row['Create Table']))
        
$sql=$row['Create Table'];
    else
    {
        
$row=array_values($row);
        
$sql=$row[1];
    }
    if(
preg_match_all('/^\s*[`"](.*?)[`"]\s+(.*?),?$/m',$sql,$matches))
    {
        foreach(
$matches[1] as $i=>$c)
        {
            if(
$c===$name)
            {
                return 
"ALTER TABLE ".$db->quoteTableName($table)
                    . 
" CHANGE ".$db->quoteColumnName($name)
                    . 
' '.$db->quoteColumnName($newName).' '.$matches[2][$i];
            }
        }
    }

    
// try to give back a SQL anyway
    
return "ALTER TABLE ".$db->quoteTableName($table)
        . 
" CHANGE ".$db->quoteColumnName($name).' '.$newName;
}

Builds a SQL statement for renaming a column.

resetSequence() 方法 (自版本 v1.1 可用)
public void resetSequence(CDbTableSchema $table, integer|null $value=NULL)
$table CDbTableSchema the table schema whose primary key sequence will be reset
$value integer|null the value for the primary key of the next new row inserted. If this is not set, the next new row's primary key will have the max value of a primary key plus one (i.e. sequence trimming).
源码: framework/db/schema/mysql/CMysqlSchema.php#89 (显示)
public function resetSequence($table,$value=null)
{
    if(
$table->sequenceName===null)
        return;
    if(
$value!==null)
        
$value=(int)$value;
    else
    {
        
$value=(int)$this->getDbConnection()
            ->
createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")
            ->
queryScalar();
        
$value++;
    }
    
$this->getDbConnection()
        ->
createCommand("ALTER TABLE {$table->rawName} AUTO_INCREMENT=$value")
        ->
execute();
}

Resets the sequence value of a table's primary key. The sequence will be reset such that the primary key of the next new row inserted will have the specified value or max value of a primary key plus one (i.e. sequence trimming).

resolveTableNames() 方法
protected void resolveTableNames(CMysqlTableSchema $table, string $name)
$table CMysqlTableSchema the table instance
$name string the unquoted table name
源码: framework/db/schema/mysql/CMysqlSchema.php#142 (显示)
protected function resolveTableNames($table,$name)
{
    
$parts=explode('.',str_replace(array('`','"'),'',$name));
    if(isset(
$parts[1]))
    {
        
$table->schemaName=$parts[0];
        
$table->name=$parts[1];
        
$table->rawName=$this->quoteTableName($table->schemaName).'.'.$this->quoteTableName($table->name);
    }
    else
    {
        
$table->name=$parts[0];
        
$table->rawName=$this->quoteTableName($table->name);
    }
}

Generates various kinds of table names.