Schema is the class for retrieving metadata from an Oracle database.
Property DetailsMap of DB errors and corresponding exceptions If left part is found in DB error message exception class from the right part is used.
public array $exceptionMap = [The row ID of the last row inserted, or the last value retrieved from the sequence object.
Character used to quote schema, table, etc. names. An array of 2 characters can be used in case starting and ending characters are different.
Method DetailsDefined 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);
}
Creates ColumnSchema instance.
protected function createColumn($column)
{
$c = $this->createColumnSchema();
$c->name = $column['COLUMN_NAME'];
$c->allowNull = $column['NULLABLE'] === 'Y';
$c->comment = $column['COLUMN_COMMENT'] === null ? '' : $column['COLUMN_COMMENT'];
$c->isPrimaryKey = false;
$this->extractColumnType($c, $column['DATA_TYPE'], $column['DATA_PRECISION'], $column['DATA_SCALE'], $column['DATA_LENGTH']);
$this->extractColumnSize($c, $column['DATA_TYPE'], $column['DATA_PRECISION'], $column['DATA_SCALE'], $column['DATA_LENGTH']);
$c->phpType = $this->getColumnPhpType($c);
if (!$c->isPrimaryKey) {
if (stripos((string) $column['DATA_DEFAULT'], 'timestamp') !== false) {
$c->defaultValue = null;
} else {
$defaultValue = (string) $column['DATA_DEFAULT'];
if ($c->type === 'timestamp' && $defaultValue === 'CURRENT_TIMESTAMP') {
$c->defaultValue = new Expression('CURRENT_TIMESTAMP');
} else {
if ($defaultValue !== null) {
if (
strlen($defaultValue) > 2
&& strncmp($defaultValue, "'", 1) === 0
&& substr($defaultValue, -1) === "'"
) {
$defaultValue = substr($defaultValue, 1, -1);
} else {
$defaultValue = trim($defaultValue);
}
}
$c->defaultValue = $c->phpTypecast($defaultValue);
}
}
}
return $c;
}
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]);
}
Creates a query builder for the database.
This method may be overridden by child classes to create a DBMS-specific query builder.
public function createQueryBuilder()
{
return Yii::createObject(QueryBuilder::className(), [$this->db]);
}
public function createSavepoint($name)
{
$this->db->createCommand("SAVEPOINT $name")->execute();
}
Extracts size, precision and scale information from column's DB type.
protected void extractColumnSize ( $column, $dbType, $precision, $scale, $length ) $column yii\db\ColumnSchema $dbType stringThe column's DB type
$precision stringTotal number of digits. This parameter is available since version 2.0.4.
$scale stringNumber of digits on the right of the decimal separator. This parameter is available since version 2.0.4.
$length stringLength for character types. This parameter is available since version 2.0.4.
protected function extractColumnSize($column, $dbType, $precision, $scale, $length)
{
$column->size = trim((string) $length) === '' ? null : (int) $length;
$column->precision = trim((string) $precision) === '' ? null : (int) $precision;
$column->scale = trim((string) $scale) === '' ? null : (int) $scale;
}
Extracts the data types for the given column.
protected void extractColumnType ( $column, $dbType, $precision, $scale, $length ) $column yii\db\ColumnSchema $dbType stringDB type
$precision stringTotal number of digits. This parameter is available since version 2.0.4.
$scale stringNumber of digits on the right of the decimal separator. This parameter is available since version 2.0.4.
$length stringLength for character types. This parameter is available since version 2.0.4.
protected function extractColumnType($column, $dbType, $precision, $scale, $length)
{
$column->dbType = $dbType;
if (strpos($dbType, 'FLOAT') !== false || strpos($dbType, 'DOUBLE') !== false) {
$column->type = 'double';
} elseif (strpos($dbType, 'NUMBER') !== false) {
if ($scale === null || $scale > 0) {
$column->type = 'decimal';
} else {
$column->type = 'integer';
}
} elseif (strpos($dbType, 'INTEGER') !== false) {
$column->type = 'integer';
} elseif (strpos($dbType, 'BLOB') !== false) {
$column->type = 'binary';
} elseif (strpos($dbType, 'CLOB') !== false) {
$column->type = 'text';
} elseif (strpos($dbType, 'TIMESTAMP') !== false) {
$column->type = 'timestamp';
} else {
$column->type = 'string';
}
}
Collects the table column metadata.
protected function findColumns($table)
{
$sql = <<<'SQL'
CT
A.COLUMN_NAME,
A.DATA_TYPE,
A.DATA_PRECISION,
A.DATA_SCALE,
(
CASE A.CHAR_USED WHEN 'C' THEN A.CHAR_LENGTH
ELSE A.DATA_LENGTH
END
) AS DATA_LENGTH,
A.NULLABLE,
A.DATA_DEFAULT,
COM.COMMENTS AS COLUMN_COMMENT
ALL_TAB_COLUMNS A
INNER JOIN ALL_OBJECTS B ON B.OWNER = A.OWNER AND LTRIM(B.OBJECT_NAME) = LTRIM(A.TABLE_NAME)
LEFT JOIN ALL_COL_COMMENTS COM ON (A.OWNER = COM.OWNER AND A.TABLE_NAME = COM.TABLE_NAME AND A.COLUMN_NAME = COM.COLUMN_NAME)
E
A.OWNER = :schemaName
AND B.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
AND B.OBJECT_NAME = :tableName
R BY A.COLUMN_ID
try {
$columns = $this->db->createCommand($sql, [
':tableName' => $table->name,
':schemaName' => $table->schemaName,
])->queryAll();
} catch (\Exception $e) {
return false;
}
if (empty($columns)) {
return false;
}
foreach ($columns as $column) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
$column = array_change_key_case($column, CASE_UPPER);
}
$c = $this->createColumn($column);
$table->columns[$c->name] = $c;
}
return true;
}
Finds constraints and fills them into TableSchema object passed.
protected function findConstraints($table)
{
$sql = <<<'SQL'
CT
D.CONSTRAINT_NAME,
D.CONSTRAINT_TYPE,
C.COLUMN_NAME,
C.POSITION,
D.R_CONSTRAINT_NAME,
E.TABLE_NAME AS TABLE_REF,
F.COLUMN_NAME AS COLUMN_REF,
C.TABLE_NAME
ALL_CONS_COLUMNS C
INNER JOIN ALL_CONSTRAINTS D ON D.OWNER = C.OWNER AND D.CONSTRAINT_NAME = C.CONSTRAINT_NAME
LEFT JOIN ALL_CONSTRAINTS E ON E.OWNER = D.R_OWNER AND E.CONSTRAINT_NAME = D.R_CONSTRAINT_NAME
LEFT JOIN ALL_CONS_COLUMNS F ON F.OWNER = E.OWNER AND F.CONSTRAINT_NAME = E.CONSTRAINT_NAME AND F.POSITION = C.POSITION
E
C.OWNER = :schemaName
AND C.TABLE_NAME = :tableName
R BY D.CONSTRAINT_NAME, C.POSITION
$command = $this->db->createCommand($sql, [
':tableName' => $table->name,
':schemaName' => $table->schemaName,
]);
$constraints = [];
foreach ($command->queryAll() as $row) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
$row = array_change_key_case($row, CASE_UPPER);
}
if ($row['CONSTRAINT_TYPE'] === 'P') {
$table->columns[$row['COLUMN_NAME']]->isPrimaryKey = true;
$table->primaryKey[] = $row['COLUMN_NAME'];
if (empty($table->sequenceName)) {
$table->sequenceName = $this->getTableSequenceName($table->name);
}
}
if ($row['CONSTRAINT_TYPE'] !== 'R') {
continue;
}
$name = $row['CONSTRAINT_NAME'];
if (!isset($constraints[$name])) {
$constraints[$name] = [
'tableName' => $row['TABLE_REF'],
'columns' => [],
];
}
$constraints[$name]['columns'][$row['COLUMN_NAME']] = $row['COLUMN_REF'];
}
foreach ($constraints as $constraint) {
$name = current(array_keys($constraint));
$table->foreignKeys[$name] = array_merge([$constraint['tableName']], $constraint['columns']);
}
}
protected function findSchemaNames()
{
static $sql = <<<'SQL'
CT "u"."USERNAME"
"DBA_USERS" "u"
E "u"."DEFAULT_TABLESPACE" NOT IN ('SYSTEM', 'SYSAUX')
R BY "u"."USERNAME" ASC
return $this->db->createCommand($sql)->queryColumn();
}
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 === '') {
$sql = <<<'SQL'
CT
TABLE_NAME
USER_TABLES
N ALL
CT
VIEW_NAME AS TABLE_NAME
USER_VIEWS
N ALL
CT
MVIEW_NAME AS TABLE_NAME
USER_MVIEWS
R BY TABLE_NAME
$command = $this->db->createCommand($sql);
} else {
$sql = <<<'SQL'
CT
OBJECT_NAME AS TABLE_NAME
ALL_OBJECTS
E
OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
AND OWNER = :schema
R BY OBJECT_NAME
$command = $this->db->createCommand($sql, [':schema' => $schema]);
}
$rows = $command->queryAll();
$names = [];
foreach ($rows as $row) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
$row = array_change_key_case($row, CASE_UPPER);
}
$names[] = $row['TABLE_NAME'];
}
return $names;
}
Returns all unique indexes for the given table.
Each array element is of the following structure:.
[
'IndexName1' => ['col1' [, ...]],
'IndexName2' => ['col2' [, ...]],
]
public function findUniqueIndexes($table)
{
$query = <<<'SQL'
CT
DIC.INDEX_NAME,
DIC.COLUMN_NAME
ALL_INDEXES DI
INNER JOIN ALL_IND_COLUMNS DIC ON DI.TABLE_NAME = DIC.TABLE_NAME AND DI.INDEX_NAME = DIC.INDEX_NAME
E
DI.UNIQUENESS = 'UNIQUE'
AND DIC.TABLE_OWNER = :schemaName
AND DIC.TABLE_NAME = :tableName
R BY DIC.TABLE_NAME, DIC.INDEX_NAME, DIC.COLUMN_POSITION
$result = [];
$command = $this->db->createCommand($query, [
':tableName' => $table->name,
':schemaName' => $table->schemaName,
]);
foreach ($command->queryAll() as $row) {
$result[$row['INDEX_NAME']][] = $row['COLUMN_NAME'];
}
return $result;
}
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) {
$sequenceName = $this->quoteSimpleTableName($sequenceName);
return $this->db->useMaster(function (Connection $db) use ($sequenceName) {
return $db->createCommand("SELECT {$sequenceName}.CURRVAL FROM DUAL")->queryScalar();
});
} else {
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);
}
protected function getTableNameParts($name)
{
return explode('.', $name);
}
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);
}
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);
}
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()
{
parent::init();
if ($this->defaultSchema === null) {
$username = $this->db->username;
if (empty($username)) {
$username = isset($this->db->masters[0]['username']) ? $this->db->masters[0]['username'] : '';
}
$this->defaultSchema = strtoupper($username);
}
}
Executes the INSERT command, returning primary key values.
public array|false insert ( $table, $columns ) $table stringThe table that new rows will be inserted into.
$columns arrayThe column data (name => value) to be inserted into the table.
return array|falsePrimary key values or false if the command fails
public function insert($table, $columns)
{
$params = [];
$returnParams = [];
$sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
$tableSchema = $this->getTableSchema($table);
$returnColumns = $tableSchema->primaryKey;
if (!empty($returnColumns)) {
$columnSchemas = $tableSchema->columns;
$returning = [];
foreach ((array) $returnColumns as $name) {
$phName = QueryBuilder::PARAM_PREFIX . (count($params) + count($returnParams));
$returnParams[$phName] = [
'column' => $name,
'value' => '',
];
if (!isset($columnSchemas[$name]) || $columnSchemas[$name]->phpType !== 'integer') {
$returnParams[$phName]['dataType'] = \PDO::PARAM_STR;
} else {
$returnParams[$phName]['dataType'] = \PDO::PARAM_INT;
}
$returnParams[$phName]['size'] = isset($columnSchemas[$name]->size) ? $columnSchemas[$name]->size : -1;
$returning[] = $this->quoteColumnName($name);
}
$sql .= ' RETURNING ' . implode(', ', $returning) . ' INTO ' . implode(', ', array_keys($returnParams));
}
$command = $this->db->createCommand($sql, $params);
$command->prepare(false);
foreach ($returnParams as $name => &$value) {
$command->pdoStatement->bindParam($name, $value['value'], $value['dataType'], $value['size']);
}
if (!$command->execute()) {
return false;
}
$result = [];
foreach ($returnParams as $value) {
$result[$value['column']] = $value['value'];
}
return $result;
}
public function isReadQuery($sql)
{
$pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
return preg_match($pattern, $sql) > 0;
}
protected function loadTableChecks($tableName)
{
return $this->loadTableConstraints($tableName, 'checks');
}
protected function loadTableDefaultValues($tableName)
{
throw new NotSupportedException('Oracle does not support default value constraints.');
}
protected function loadTableForeignKeys($tableName)
{
return $this->loadTableConstraints($tableName, 'foreignKeys');
}
protected function loadTableIndexes($tableName)
{
static $sql = <<<'SQL'
CT
"ui"."INDEX_NAME" AS "name",
"uicol"."COLUMN_NAME" AS "column_name",
CASE "ui"."UNIQUENESS" WHEN 'UNIQUE' THEN 1 ELSE 0 END AS "index_is_unique",
CASE WHEN "uc"."CONSTRAINT_NAME" IS NOT NULL THEN 1 ELSE 0 END AS "index_is_primary"
"SYS"."USER_INDEXES" "ui"
JOIN "SYS"."USER_IND_COLUMNS" "uicol"
ON "uicol"."INDEX_NAME" = "ui"."INDEX_NAME"
JOIN "SYS"."USER_CONSTRAINTS" "uc"
ON "uc"."OWNER" = "ui"."TABLE_OWNER" AND "uc"."CONSTRAINT_NAME" = "ui"."INDEX_NAME" AND "uc"."CONSTRAINT_TYPE" = 'P'
E "ui"."TABLE_OWNER" = :schemaName AND "ui"."TABLE_NAME" = :tableName
R BY "uicol"."COLUMN_POSITION" ASC
$resolvedName = $this->resolveTableName($tableName);
$indexes = $this->db->createCommand($sql, [
':schemaName' => $resolvedName->schemaName,
':tableName' => $resolvedName->name,
])->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);
if ($this->findColumns($table)) {
$this->findConstraints($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);
}
Defined in: yii\db\Schema::quoteColumnName()
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.
See also quoteSimpleColumnName().
public function quoteColumnName($name)
{
if (strpos($name, '(') !== false || strpos($name, '[[') !== false) {
return $name;
}
if (($pos = strrpos($name, '.')) !== false) {
$prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
$name = substr($name, $pos + 1);
} else {
$prefix = '';
}
if (strpos($name, '{{') !== false) {
return $name;
}
return $prefix . $this->quoteSimpleColumnName($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;
}
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)
{
return strpos($name, '"') !== false ? $name : '"' . $name . '"';
}
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 = explode('.', str_replace('"', '', $name));
if (isset($parts[1])) {
$resolvedName->schemaName = $parts[0];
$resolvedName->name = $parts[1];
} else {
$resolvedName->schemaName = $this->defaultSchema;
$resolvedName->name = $name;
}
$resolvedName->fullName = ($resolvedName->schemaName !== $this->defaultSchema ? $resolvedName->schemaName . '.' : '') . $resolvedName->name;
return $resolvedName;
}
Resolves the table name and schema name (if any).
protected function resolveTableNames($table, $name)
{
$parts = explode('.', str_replace('"', '', $name));
if (isset($parts[1])) {
$table->schemaName = $parts[0];
$table->name = $parts[1];
} else {
$table->schemaName = $this->defaultSchema;
$table->name = $name;
}
$table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
}
public function rollBackSavepoint($name)
{
$this->db->createCommand("ROLLBACK TO SAVEPOINT $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