Class yii\db\pgsql\Schema
Inheritance | yii\db\pgsql\Schema » yii\db\Schema » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable, yii\db\ConstraintFinderInterface |
Uses Traits | yii\db\ConstraintFinderTrait, yii\db\ViewFinderTrait |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/Schema.php |
Schema is the class for retrieving metadata from a PostgreSQL database (version 9.x and above).
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$columnQuoteCharacter | string|string[] | Character used to quote column names. | yii\db\Schema |
$columnSchemaClass | string|array | Column schema class or class config | yii\db\pgsql\Schema |
$db | yii\db\Connection | The database connection | yii\db\Schema |
$defaultSchema | string | The default schema used for the current session. | yii\db\pgsql\Schema |
$exceptionMap | array | Map of DB errors and corresponding exceptions If left part is found in DB error message exception class from the right part is used. | yii\db\Schema |
$lastInsertID | string | The row ID of the last row inserted, or the last value retrieved from the sequence object. | yii\db\Schema |
$queryBuilder | yii\db\QueryBuilder | The query builder for this connection. | yii\db\Schema |
$schemaChecks | \yii\db\CheckConstraint[][] | Check constraints for all tables in the database. | yii\db\ConstraintFinderTrait |
$schemaDefaultValues | yii\db\DefaultValueConstraint[] | Default value constraints for all tables in the database. | yii\db\ConstraintFinderTrait |
$schemaForeignKeys | \yii\db\ForeignKeyConstraint[][] | Foreign keys for all tables in the database. | yii\db\ConstraintFinderTrait |
$schemaIndexes | \yii\db\IndexConstraint[][] | Indexes for all tables in the database. | yii\db\ConstraintFinderTrait |
$schemaNames | string[] | All schema names in the database, except system schemas. | yii\db\Schema |
$schemaPrimaryKeys | yii\db\Constraint[] | Primary keys for all tables in the database. | yii\db\ConstraintFinderTrait |
$schemaUniques | \yii\db\IndexConstraint[][] | Unique constraints for all tables in the database. | yii\db\ConstraintFinderTrait |
$serverVersion | string | Server version as a string. | yii\db\Schema |
$tableNames | string[] | All table names in the database. | yii\db\Schema |
$tableQuoteCharacter | string|string[] | Character used to quote schema, table, etc. | yii\db\pgsql\Schema |
$tableSchemas | yii\db\TableSchema[] | The metadata for all tables in the database. | yii\db\Schema |
$transactionIsolationLevel | string | The transaction isolation level to use for this transaction. | yii\db\Schema |
$typeMap | array | Mapping from physical column types (keys) to abstract column types (values) | yii\db\pgsql\Schema |
$viewNames | string[] | All view names in the database. | yii\db\ViewFinderTrait |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\BaseObject |
__construct() | Constructor. | 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() | Returns the fully qualified name of this class. | yii\base\BaseObject |
convertException() | Converts a DB exception to a more concrete one if possible. | yii\db\Schema |
createColumnSchemaBuilder() | Create a column schema builder instance giving the type and value precision. | yii\db\Schema |
createQueryBuilder() | Creates a query builder for the PostgreSQL database. | yii\db\pgsql\Schema |
createSavepoint() | Creates a new savepoint. | yii\db\Schema |
findUniqueIndexes() | Returns all unique indexes for the given table. | yii\db\pgsql\Schema |
getLastInsertID() | Returns the ID of the last inserted row or sequence value. | yii\db\Schema |
getPdoType() | Determines the PDO type for the given PHP data value. | yii\db\Schema |
getQueryBuilder() | yii\db\Schema | |
getRawTableName() | Returns the actual name of a given table name. | yii\db\Schema |
getSchemaChecks() | Returns check constraints for all tables in the database. | yii\db\ConstraintFinderTrait |
getSchemaDefaultValues() | Returns default value constraints for all tables in the database. | yii\db\ConstraintFinderTrait |
getSchemaForeignKeys() | Returns foreign keys for all tables in the database. | yii\db\ConstraintFinderTrait |
getSchemaIndexes() | Returns indexes for all tables in the database. | yii\db\ConstraintFinderTrait |
getSchemaNames() | Returns all schema names in the database, except system schemas. | yii\db\Schema |
getSchemaPrimaryKeys() | Returns primary keys for all tables in the database. | yii\db\ConstraintFinderTrait |
getSchemaUniques() | Returns unique constraints for all tables in the database. | yii\db\ConstraintFinderTrait |
getServerVersion() | Returns a server version as a string comparable by \version_compare(). | yii\db\Schema |
getTableChecks() | Obtains the check constraints information for the named table. | yii\db\ConstraintFinderTrait |
getTableDefaultValues() | Obtains the default value constraints information for the named table. | yii\db\ConstraintFinderTrait |
getTableForeignKeys() | Obtains the foreign keys information for the named table. | yii\db\ConstraintFinderTrait |
getTableIndexes() | Obtains the indexes information for the named table. | yii\db\ConstraintFinderTrait |
getTableNames() | Returns all table names in the database. | yii\db\Schema |
getTablePrimaryKey() | Obtains the primary key for the named table. | yii\db\ConstraintFinderTrait |
getTableSchema() | Obtains the metadata for the named table. | yii\db\Schema |
getTableSchemas() | Returns the metadata for all tables in the database. | yii\db\Schema |
getTableUniques() | Obtains the unique constraints information for the named table. | yii\db\ConstraintFinderTrait |
getViewNames() | Returns all view names in the database. | yii\db\ViewFinderTrait |
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. | yii\db\pgsql\Schema |
isReadQuery() | Returns a value indicating whether a SQL statement is for read purpose. | yii\db\Schema |
quoteColumnName() | Quotes a column name for use in a query. | yii\db\Schema |
quoteSimpleColumnName() | Quotes a simple column name for use in a query. | yii\db\Schema |
quoteSimpleTableName() | Quotes a simple table name for use in a query. | yii\db\Schema |
quoteTableName() | Quotes a table name for use in a query. | yii\db\Schema |
quoteValue() | Quotes a string value for use in a query. | yii\db\Schema |
refresh() | Refreshes the schema. | yii\db\Schema |
refreshTableSchema() | Refreshes the particular table schema. | yii\db\Schema |
releaseSavepoint() | Releases an existing savepoint. | yii\db\Schema |
rollBackSavepoint() | Rolls back to a previously created savepoint. | yii\db\Schema |
setTransactionIsolationLevel() | Sets the isolation level of the current transaction. | yii\db\Schema |
supportsSavepoint() | yii\db\Schema | |
unquoteSimpleColumnName() | Unquotes a simple column name. | yii\db\Schema |
unquoteSimpleTableName() | Unquotes a simple table name. | yii\db\Schema |
Protected Methods
Method | Description | Defined By |
---|---|---|
createColumnSchema() | Creates a column schema for the database. | yii\db\Schema |
findColumns() | Collects the metadata of table columns. | yii\db\pgsql\Schema |
findConstraints() | Collects the foreign key column details for the given table. | yii\db\pgsql\Schema |
findSchemaNames() | Returns all schema names in the database, including the default one but not system schemas. | yii\db\pgsql\Schema |
findTableNames() | Returns all table names in the database. | yii\db\pgsql\Schema |
findViewNames() | {@inheritdoc] | yii\db\pgsql\Schema |
getCacheKey() | Returns the cache key for the specified table name. | yii\db\Schema |
getCacheTag() | Returns the cache tag name. | yii\db\Schema |
getColumnPhpType() | Extracts the PHP type from abstract DB type. | yii\db\Schema |
getSchemaMetadata() | Returns the metadata of the given type for all tables in the given schema. | yii\db\ConstraintFinderTrait |
getTableMetadata() | Returns the metadata of the given type for the given table. | yii\db\ConstraintFinderTrait |
getTableNameParts() | Splits full table name into parts | yii\db\Schema |
getUniqueIndexInformation() | Gets information about given table unique indexes. | yii\db\pgsql\Schema |
loadColumnSchema() | Loads the column information into a yii\db\pgsql\ColumnSchema object. | yii\db\pgsql\Schema |
loadTableChecks() | yii\db\pgsql\Schema | |
loadTableDefaultValues() | yii\db\pgsql\Schema | |
loadTableForeignKeys() | yii\db\pgsql\Schema | |
loadTableIndexes() | yii\db\pgsql\Schema | |
loadTablePrimaryKey() | yii\db\pgsql\Schema | |
loadTableSchema() | Loads the metadata for the specified table. | yii\db\pgsql\Schema |
loadTableUniques() | yii\db\pgsql\Schema | |
normalizePdoRowKeyCase() | Changes row's array key case to lower if PDO's one is set to uppercase. | yii\db\Schema |
resolveTableName() | Resolves the table name and schema name (if any). | yii\db\pgsql\Schema |
resolveTableNames() | Resolves the table name and schema name (if any). | yii\db\pgsql\Schema |
setTableMetadata() | Sets the metadata of the given type for the given table. | yii\db\Schema |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
SCHEMA_CACHE_VERSION | 1 | Schema cache version, to detect incompatibilities in cached values when the data format of the cache changes. | yii\db\Schema |
TYPE_BIGINT | 'bigint' | yii\db\Schema | |
TYPE_BIGPK | 'bigpk' | yii\db\Schema | |
TYPE_BINARY | 'binary' | yii\db\Schema | |
TYPE_BOOLEAN | 'boolean' | yii\db\Schema | |
TYPE_CHAR | 'char' | yii\db\Schema | |
TYPE_DATE | 'date' | yii\db\Schema | |
TYPE_DATETIME | 'datetime' | yii\db\Schema | |
TYPE_DECIMAL | 'decimal' | yii\db\Schema | |
TYPE_DOUBLE | 'double' | yii\db\Schema | |
TYPE_FLOAT | 'float' | yii\db\Schema | |
TYPE_INTEGER | 'integer' | yii\db\Schema | |
TYPE_JSON | 'json' | yii\db\Schema | |
TYPE_JSONB | 'jsonb' | yii\db\pgsql\Schema | |
TYPE_MONEY | 'money' | yii\db\Schema | |
TYPE_PK | 'pk' | yii\db\Schema | |
TYPE_SMALLINT | 'smallint' | yii\db\Schema | |
TYPE_STRING | 'string' | yii\db\Schema | |
TYPE_TEXT | 'text' | yii\db\Schema | |
TYPE_TIME | 'time' | yii\db\Schema | |
TYPE_TIMESTAMP | 'timestamp' | yii\db\Schema | |
TYPE_TINYINT | 'tinyint' | yii\db\Schema | |
TYPE_UBIGPK | 'ubigpk' | yii\db\Schema | |
TYPE_UPK | 'upk' | yii\db\Schema |
Property Details
Column schema class or class config
The default schema used for the current session.
Character used to quote schema, table, etc. names. An array of 2 characters can be used in case starting and ending characters are different.
Mapping from physical column types (keys) to abstract column types (values)
See also https://www.postgresql.org/docs/current/datatype.html#DATATYPE-TABLE.
'bit' => self::TYPE_INTEGER,
'bit varying' => self::TYPE_INTEGER,
'varbit' => self::TYPE_INTEGER,
'bool' => self::TYPE_BOOLEAN,
'boolean' => self::TYPE_BOOLEAN,
'box' => self::TYPE_STRING,
'circle' => self::TYPE_STRING,
'point' => self::TYPE_STRING,
'line' => self::TYPE_STRING,
'lseg' => self::TYPE_STRING,
'polygon' => self::TYPE_STRING,
'path' => self::TYPE_STRING,
'character' => self::TYPE_CHAR,
'char' => self::TYPE_CHAR,
'bpchar' => self::TYPE_CHAR,
'character varying' => self::TYPE_STRING,
'varchar' => self::TYPE_STRING,
'text' => self::TYPE_TEXT,
'bytea' => self::TYPE_BINARY,
'cidr' => self::TYPE_STRING,
'inet' => self::TYPE_STRING,
'macaddr' => self::TYPE_STRING,
'real' => self::TYPE_FLOAT,
'float4' => self::TYPE_FLOAT,
'double precision' => self::TYPE_DOUBLE,
'float8' => self::TYPE_DOUBLE,
'decimal' => self::TYPE_DECIMAL,
'numeric' => self::TYPE_DECIMAL,
'money' => self::TYPE_MONEY,
'smallint' => self::TYPE_SMALLINT,
'int2' => self::TYPE_SMALLINT,
'int4' => self::TYPE_INTEGER,
'int' => self::TYPE_INTEGER,
'integer' => self::TYPE_INTEGER,
'bigint' => self::TYPE_BIGINT,
'int8' => self::TYPE_BIGINT,
'oid' => self::TYPE_BIGINT,
'smallserial' => self::TYPE_SMALLINT,
'serial2' => self::TYPE_SMALLINT,
'serial4' => self::TYPE_INTEGER,
'serial' => self::TYPE_INTEGER,
'bigserial' => self::TYPE_BIGINT,
'serial8' => self::TYPE_BIGINT,
'pg_lsn' => self::TYPE_BIGINT,
'date' => self::TYPE_DATE,
'interval' => self::TYPE_STRING,
'time without time zone' => self::TYPE_TIME,
'time' => self::TYPE_TIME,
'time with time zone' => self::TYPE_TIME,
'timetz' => self::TYPE_TIME,
'timestamp without time zone' => self::TYPE_TIMESTAMP,
'timestamp' => self::TYPE_TIMESTAMP,
'timestamp with time zone' => self::TYPE_TIMESTAMP,
'timestamptz' => self::TYPE_TIMESTAMP,
'abstime' => self::TYPE_TIMESTAMP,
'tsquery' => self::TYPE_STRING,
'tsvector' => self::TYPE_STRING,
'txid_snapshot' => self::TYPE_STRING,
'unknown' => self::TYPE_STRING,
'uuid' => self::TYPE_STRING,
'json' => self::TYPE_JSON,
'jsonb' => self::TYPE_JSON,
'xml' => self::TYPE_STRING,
]
Method Details
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 mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
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:
- Initializes the object with the given configuration
$config
. - Call init().
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
public void __construct ( $config = [] ) | ||
$config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\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 mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
} elseif (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\BaseObject::__isset()
Checks if a property is set, i.e. defined and not null.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($object->property)
.
Note that if the property is not defined, false will be returned.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set (not null). |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
return false;
}
Defined in: yii\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 void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
}
Defined in: yii\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.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
}
}
Defined in: yii\base\BaseObject::canGetProperty()
Returns a value indicating whether a property can be read.
A property is readable if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true)
{
return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}
Defined in: yii\base\BaseObject::canSetProperty()
Returns a value indicating whether a property can be set.
A property is writable if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true)
{
return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
Defined in: yii\db\Schema::convertException()
Converts a DB exception to a more concrete one if possible.
public yii\db\Exception convertException ( Exception $e, $rawSql ) | ||
$e | Exception | |
$rawSql | string |
SQL that produced exception |
public function convertException(\Exception $e, $rawSql)
{
if ($e instanceof Exception) {
return $e;
}
$exceptionClass = '\yii\db\Exception';
foreach ($this->exceptionMap as $error => $class) {
if (strpos($e->getMessage(), $error) !== false) {
$exceptionClass = $class;
}
}
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
return new $exceptionClass($message, $errorInfo, $e->getCode(), $e);
}
Defined in: yii\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 yii\db\ColumnSchema createColumnSchema ( ) | ||
return | yii\db\ColumnSchema |
Column schema instance. |
---|---|---|
throws | yii\base\InvalidConfigException |
if a column schema class cannot be created. |
protected function createColumnSchema()
{
return Yii::createObject($this->columnSchemaClass);
}
Defined in: yii\db\Schema::createColumnSchemaBuilder()
Create a column schema builder instance giving the type and value precision.
This method may be overridden by child classes to create a DBMS-specific column schema builder.
public yii\db\ColumnSchemaBuilder createColumnSchemaBuilder ( $type, $length = null ) | ||
$type | string |
Type of the column. See yii\db\ColumnSchemaBuilder::$type. |
$length | integer|string|array|null |
Length or precision of the column. See yii\db\ColumnSchemaBuilder::$length. |
return | yii\db\ColumnSchemaBuilder |
Column schema builder instance |
---|
public function createColumnSchemaBuilder($type, $length = null)
{
return Yii::createObject(ColumnSchemaBuilder::className(), [$type, $length]);
}
Creates a query builder for the PostgreSQL database.
public yii\db\pgsql\QueryBuilder createQueryBuilder ( ) | ||
return | yii\db\pgsql\QueryBuilder |
Query builder instance |
---|
public function createQueryBuilder()
{
return Yii::createObject(QueryBuilder::className(), [$this->db]);
}
Defined in: yii\db\Schema::createSavepoint()
Creates a new savepoint.
public void createSavepoint ( $name ) | ||
$name | string |
The savepoint name |
public function createSavepoint($name)
{
$this->db->createCommand("SAVEPOINT $name")->execute();
}
Collects the metadata of table columns.
protected boolean findColumns ( $table ) | ||
$table | yii\db\TableSchema |
The table metadata |
return | boolean |
Whether the table exists in the database |
---|
protected function findColumns($table)
{
$tableName = $this->db->quoteValue($table->name);
$schemaName = $this->db->quoteValue($table->schemaName);
$orIdentity = '';
if (version_compare($this->db->serverVersion, '12.0', '>=')) {
$orIdentity = 'OR attidentity != \'\'';
}
$sql = <<<SQL
CT
d.nspname AS table_schema,
c.relname AS table_name,
a.attname AS column_name,
COALESCE(td.typname, tb.typname, t.typname) AS data_type,
COALESCE(td.typtype, tb.typtype, t.typtype) AS type_type,
(SELECT nspname FROM pg_namespace WHERE oid = COALESCE(td.typnamespace, tb.typnamespace, t.typnamespace)) AS type_scheme,
a.attlen AS character_maximum_length,
pg_catalog.col_description(c.oid, a.attnum) AS column_comment,
a.atttypmod AS modifier,
a.attnotnull = false AS is_nullable,
CAST(pg_get_expr(ad.adbin, ad.adrelid) AS varchar) AS column_default,
coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval',false) {$orIdentity} AS is_autoinc,
pg_get_serial_sequence(quote_ident(d.nspname) || '.' || quote_ident(c.relname), a.attname) AS sequence_name,
CASE WHEN COALESCE(td.typtype, tb.typtype, t.typtype) = 'e'::char
THEN array_to_string((SELECT array_agg(enumlabel) FROM pg_enum WHERE enumtypid = COALESCE(td.oid, tb.oid, a.atttypid))::varchar[], ',')
ELSE NULL
END AS enum_values,
CASE atttypid
WHEN 21 /*int2*/ THEN 16
WHEN 23 /*int4*/ THEN 32
WHEN 20 /*int8*/ THEN 64
WHEN 1700 /*numeric*/ THEN
CASE WHEN atttypmod = -1
THEN null
ELSE ((atttypmod - 4) >> 16) & 65535
END
WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/
WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/
ELSE null
END AS numeric_precision,
CASE
WHEN atttypid IN (21, 23, 20) THEN 0
WHEN atttypid IN (1700) THEN
CASE
WHEN atttypmod = -1 THEN null
ELSE (atttypmod - 4) & 65535
END
ELSE null
END AS numeric_scale,
CAST(
information_schema._pg_char_max_length(information_schema._pg_truetypid(a, t), information_schema._pg_truetypmod(a, t))
AS numeric
) AS size,
a.attnum = any (ct.conkey) as is_pkey,
COALESCE(NULLIF(a.attndims, 0), NULLIF(t.typndims, 0), (t.typcategory='A')::int) AS dimension
pg_class c
LEFT JOIN pg_attribute a ON a.attrelid = c.oid
LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
LEFT JOIN pg_type t ON a.atttypid = t.oid
LEFT JOIN pg_type tb ON (a.attndims > 0 OR t.typcategory='A') AND t.typelem > 0 AND t.typelem = tb.oid OR t.typbasetype > 0 AND t.typbasetype = tb.oid
LEFT JOIN pg_type td ON t.typndims > 0 AND t.typbasetype > 0 AND tb.typelem = td.oid
LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
LEFT JOIN pg_constraint ct ON ct.conrelid = c.oid AND ct.contype = 'p'
E
a.attnum > 0 AND t.typname != '' AND NOT a.attisdropped
AND c.relname = {$tableName}
AND d.nspname = {$schemaName}
R BY
a.attnum;
$columns = $this->db->createCommand($sql)->queryAll();
if (empty($columns)) {
return false;
}
foreach ($columns as $column) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_UPPER) {
$column = array_change_key_case($column, CASE_LOWER);
}
$column = $this->loadColumnSchema($column);
$table->columns[$column->name] = $column;
if ($column->isPrimaryKey) {
$table->primaryKey[] = $column->name;
if ($table->sequenceName === null) {
$table->sequenceName = $column->sequenceName;
}
$column->defaultValue = null;
} elseif ($column->defaultValue) {
if (
in_array($column->type, [self::TYPE_TIMESTAMP, self::TYPE_DATE, self::TYPE_TIME], true) &&
in_array(
strtoupper($column->defaultValue),
['NOW()', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME'],
true
)
) {
$column->defaultValue = new Expression($column->defaultValue);
} elseif ($column->type === 'boolean') {
$column->defaultValue = ($column->defaultValue === 'true');
} elseif (preg_match("/^B'(.*?)'::/", $column->defaultValue, $matches)) {
$column->defaultValue = bindec($matches[1]);
} elseif (preg_match("/^'(\d+)'::\"bit\"$/", $column->defaultValue, $matches)) {
$column->defaultValue = bindec($matches[1]);
} elseif (preg_match("/^'(.*?)'::/", $column->defaultValue, $matches)) {
$column->defaultValue = $column->phpTypecast($matches[1]);
} elseif (preg_match('/^(\()?(.*?)(?(1)\))(?:::.+)?$/', $column->defaultValue, $matches)) {
if ($matches[2] === 'NULL') {
$column->defaultValue = null;
} else {
$column->defaultValue = $column->phpTypecast($matches[2]);
}
} else {
$column->defaultValue = $column->phpTypecast($column->defaultValue);
}
}
}
return true;
}
Collects the foreign key column details for the given table.
protected void findConstraints ( $table ) | ||
$table | yii\db\TableSchema |
The table metadata |
protected function findConstraints($table)
{
$tableName = $this->quoteValue($table->name);
$tableSchema = $this->quoteValue($table->schemaName);
//We need to extract the constraints de hard way since:
//https://www.postgresql.org/message-id/26677.1086673982@sss.pgh.pa.us
$sql = <<<SQL
ct
ct.conname as constraint_name,
a.attname as column_name,
fc.relname as foreign_table_name,
fns.nspname as foreign_table_schema,
fa.attname as foreign_column_name
(SELECT ct.conname, ct.conrelid, ct.confrelid, ct.conkey, ct.contype, ct.confkey, generate_subscripts(ct.conkey, 1) AS s
FROM pg_constraint ct
) AS ct
inner join pg_class c on c.oid=ct.conrelid
inner join pg_namespace ns on c.relnamespace=ns.oid
inner join pg_attribute a on a.attrelid=ct.conrelid and a.attnum = ct.conkey[ct.s]
left join pg_class fc on fc.oid=ct.confrelid
left join pg_namespace fns on fc.relnamespace=fns.oid
left join pg_attribute fa on fa.attrelid=ct.confrelid and fa.attnum = ct.confkey[ct.s]
e
ct.contype='f'
and c.relname={$tableName}
and ns.nspname={$tableSchema}
r by
fns.nspname, fc.relname, a.attnum
$constraints = [];
foreach ($this->db->createCommand($sql)->queryAll() as $constraint) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_UPPER) {
$constraint = array_change_key_case($constraint, CASE_LOWER);
}
if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
$foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
} else {
$foreignTable = $constraint['foreign_table_name'];
}
$name = $constraint['constraint_name'];
if (!isset($constraints[$name])) {
$constraints[$name] = [
'tableName' => $foreignTable,
'columns' => [],
];
}
$constraints[$name]['columns'][$constraint['column_name']] = $constraint['foreign_column_name'];
}
foreach ($constraints as $name => $constraint) {
$table->foreignKeys[$name] = array_merge([$constraint['tableName']], $constraint['columns']);
}
}
Returns all schema names in the database, including the default one but not system schemas.
This method should be overridden by child classes in order to support this feature because the default implementation simply throws an exception.
protected array findSchemaNames ( ) | ||
return | array |
All schema names in the database, except system schemas. |
---|---|---|
throws | yii\base\NotSupportedException |
if this method is not supported by the DBMS. |
protected function findSchemaNames()
{
static $sql = <<<'SQL'
CT "ns"."nspname"
"pg_namespace" AS "ns"
E "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%'
R BY "ns"."nspname" 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 | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema. |
return | array |
All table names in the database. The names have NO schema name prefix. |
---|---|---|
throws | yii\base\NotSupportedException |
if this method is not supported by the DBMS. |
protected function findTableNames($schema = '')
{
if ($schema === '') {
$schema = $this->defaultSchema;
}
$sql = <<<'SQL'
CT c.relname AS table_name
pg_class c
R JOIN pg_namespace ns ON ns.oid = c.relnamespace
E ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f', 'p')
R BY c.relname
return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
}
Returns all unique indexes for the given table.
Each array element is of the following structure:
[
'IndexName1' => ['col1' [, ...]],
'IndexName2' => ['col2' [, ...]],
]
public array findUniqueIndexes ( $table ) | ||
$table | yii\db\TableSchema |
The table metadata |
return | array |
All unique indexes for the given table. |
---|
public function findUniqueIndexes($table)
{
$uniqueIndexes = [];
foreach ($this->getUniqueIndexInformation($table) as $row) {
if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_UPPER) {
$row = array_change_key_case($row, CASE_LOWER);
}
$column = $row['columnname'];
if (strncmp($column, '"', 1) === 0) {
// postgres will quote names that are not lowercase-only
// https://github.com/yiisoft/yii2/issues/10613
$column = substr($column, 1, -1);
}
$uniqueIndexes[$row['indexname']][] = $column;
}
return $uniqueIndexes;
}
{@inheritdoc]
protected void findViewNames ( $schema = '' ) | ||
$schema |
protected function findViewNames($schema = '')
{
if ($schema === '') {
$schema = $this->defaultSchema;
}
$sql = <<<'SQL'
CT c.relname AS table_name
pg_class c
R JOIN pg_namespace ns ON ns.oid = c.relnamespace
E ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm')
R BY c.relname
return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
}
Defined in: yii\db\Schema::getCacheKey()
Returns the cache key for the specified table name.
protected mixed getCacheKey ( $name ) | ||
$name | string |
The table name. |
return | mixed |
The cache key. |
---|
protected function getCacheKey($name)
{
return [
__CLASS__,
$this->db->dsn,
$this->db->username,
$this->getRawTableName($name),
];
}
Defined in: yii\db\Schema::getCacheTag()
Returns the cache tag name.
This allows refresh() to invalidate all cached table schemas.
protected string getCacheTag ( ) | ||
return | string |
The cache tag name |
---|
protected function getCacheTag()
{
return md5(serialize([
__CLASS__,
$this->db->dsn,
$this->db->username,
]));
}
Defined in: yii\db\Schema::getColumnPhpType()
Extracts the PHP type from abstract DB type.
protected string getColumnPhpType ( $column ) | ||
$column | yii\db\ColumnSchema |
The column schema information |
return | string |
PHP type name |
---|
protected function getColumnPhpType($column)
{
static $typeMap = [
// abstract type => php type
self::TYPE_TINYINT => 'integer',
self::TYPE_SMALLINT => 'integer',
self::TYPE_INTEGER => 'integer',
self::TYPE_BIGINT => 'integer',
self::TYPE_BOOLEAN => 'boolean',
self::TYPE_FLOAT => 'double',
self::TYPE_DOUBLE => 'double',
self::TYPE_BINARY => 'resource',
self::TYPE_JSON => 'array',
];
if (isset($typeMap[$column->type])) {
if ($column->type === 'bigint') {
return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string';
} elseif ($column->type === 'integer') {
return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer';
}
return $typeMap[$column->type];
}
return 'string';
}
Defined in: yii\db\Schema::getLastInsertID()
Returns the ID of the last inserted row or sequence value.
See also https://www.php.net/manual/en/function.PDO-lastInsertId.php.
public string getLastInsertID ( $sequenceName = '' ) | ||
$sequenceName | string |
Name of the sequence object (required by some DBMS) |
return | string |
The row ID of the last row inserted, or the last value retrieved from the sequence object |
---|---|---|
throws | yii\base\InvalidCallException |
if the DB connection is not active |
public function getLastInsertID($sequenceName = '')
{
if ($this->db->isActive) {
return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName));
}
throw new InvalidCallException('DB Connection is not active.');
}
Defined in: yii\db\Schema::getPdoType()
Determines the PDO type for the given PHP data value.
public integer getPdoType ( $data ) | ||
$data | mixed |
The data whose PDO type is to be determined |
return | integer |
The PDO type |
---|
public function getPdoType($data)
{
static $typeMap = [
// php type => PDO type
'boolean' => \PDO::PARAM_BOOL,
'integer' => \PDO::PARAM_INT,
'string' => \PDO::PARAM_STR,
'resource' => \PDO::PARAM_LOB,
'NULL' => \PDO::PARAM_NULL,
];
$type = gettype($data);
return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
}
Defined in: yii\db\Schema::getQueryBuilder()
public yii\db\QueryBuilder getQueryBuilder ( ) | ||
return | yii\db\QueryBuilder |
The query builder for this connection. |
---|
public function getQueryBuilder()
{
if ($this->_builder === null) {
$this->_builder = $this->createQueryBuilder();
}
return $this->_builder;
}
Defined in: yii\db\Schema::getRawTableName()
Returns the actual name of a given table name.
This method will strip off curly brackets from the given table name and replace the percentage character '%' with yii\db\Connection::$tablePrefix.
public string getRawTableName ( $name ) | ||
$name | string |
The table name to be converted |
return | string |
The real name of the given table name |
---|
public function getRawTableName($name)
{
if (strpos($name, '{{') !== false) {
$name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
return str_replace('%', $this->db->tablePrefix, $name);
}
return $name;
}
Defined in: yii\db\ConstraintFinderTrait::getSchemaChecks()
Returns check constraints for all tables in the database.
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 | boolean |
Whether 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);
}
Defined in: yii\db\ConstraintFinderTrait::getSchemaDefaultValues()
Returns default value constraints for all tables in the database.
public yii\db\DefaultValueConstraint[] getSchemaDefaultValues ( $schema = '', $refresh = false ) | ||
$schema | string |
The schema of the tables. Defaults to empty string, meaning the current or default schema name. |
$refresh | boolean |
Whether to fetch the latest available table schemas. If this is false, cached data may be returned if available. |
return | yii\db\DefaultValueConstraint[] |
Default value constraints for all tables in the database. Each array element is an array of yii\db\DefaultValueConstraint or its child classes. |
---|
public function getSchemaDefaultValues($schema = '', $refresh = false)
{
return $this->getSchemaMetadata($schema, 'defaultValues', $refresh);
}
Defined in: yii\db\ConstraintFinderTrait::getSchemaForeignKeys()
Returns foreign keys for all tables in the database.
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 | boolean |
Whether 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);
}
Defined in: yii\db\ConstraintFinderTrait::getSchemaIndexes()
Returns indexes for all tables in the database.
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 | boolean |
Whether 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);
}
Defined in: yii\db\ConstraintFinderTrait::getSchemaMetadata()
Returns the metadata of the given type for all tables in the given schema.
protected abstract array getSchemaMetadata ( $schema, $type, $refresh ) | ||
$schema | string |
The schema of the metadata. Defaults to empty string, meaning the current or default schema name. |
$type | string |
Metadata type. |
$refresh | boolean |
Whether to fetch the latest available table metadata. If this is |
return | array |
Array of metadata. |
---|
abstract protected function getSchemaMetadata($schema, $type, $refresh);
Defined in: yii\db\Schema::getSchemaNames()
Returns all schema names in the database, except system schemas.
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;
}
Defined in: yii\db\ConstraintFinderTrait::getSchemaPrimaryKeys()
Returns primary keys for all tables in the database.
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 | boolean |
Whether to fetch the latest available table schemas. If this is |
return | yii\db\Constraint[] |
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);
}
Defined in: yii\db\ConstraintFinderTrait::getSchemaUniques()
Returns unique constraints for all tables in the database.
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 | boolean |
Whether 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);
}
Defined in: yii\db\Schema::getServerVersion()
Returns a server version as a string comparable by \version_compare().
public string getServerVersion ( ) | ||
return | string |
Server version as a string. |
---|
public function getServerVersion()
{
if ($this->_serverVersion === null) {
$this->_serverVersion = $this->db->getSlavePdo(true)->getAttribute(\PDO::ATTR_SERVER_VERSION);
}
return $this->_serverVersion;
}
Defined in: yii\db\ConstraintFinderTrait::getTableChecks()
Obtains the check constraints information for the named table.
public yii\db\CheckConstraint[] getTableChecks ( $name, $refresh = false ) | ||
$name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
$refresh | boolean |
Whether to reload the information even if it is found in the cache. |
return | yii\db\CheckConstraint[] |
Table check constraints. |
---|
public function getTableChecks($name, $refresh = false)
{
return $this->getTableMetadata($name, 'checks', $refresh);
}
Defined in: yii\db\ConstraintFinderTrait::getTableDefaultValues()
Obtains the default value constraints information for the named table.
public yii\db\DefaultValueConstraint[] getTableDefaultValues ( $name, $refresh = false ) | ||
$name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
$refresh | boolean |
Whether to reload the information even if it is found in the cache. |
return | yii\db\DefaultValueConstraint[] |
Table default value constraints. |
---|
public function getTableDefaultValues($name, $refresh = false)
{
return $this->getTableMetadata($name, 'defaultValues', $refresh);
}
Defined in: yii\db\ConstraintFinderTrait::getTableForeignKeys()
Obtains the foreign keys information for the named table.
public yii\db\ForeignKeyConstraint[] getTableForeignKeys ( $name, $refresh = false ) | ||
$name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
$refresh | boolean |
Whether to reload the information even if it is found in the cache. |
return | yii\db\ForeignKeyConstraint[] |
Table foreign keys. |
---|
public function getTableForeignKeys($name, $refresh = false)
{
return $this->getTableMetadata($name, 'foreignKeys', $refresh);
}
Defined in: yii\db\ConstraintFinderTrait::getTableIndexes()
Obtains the indexes information for the named table.
public yii\db\IndexConstraint[] getTableIndexes ( $name, $refresh = false ) | ||
$name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
$refresh | boolean |
Whether to reload the information even if it is found in the cache. |
return | yii\db\IndexConstraint[] |
Table indexes. |
---|
public function getTableIndexes($name, $refresh = false)
{
return $this->getTableMetadata($name, 'indexes', $refresh);
}
Defined in: yii\db\ConstraintFinderTrait::getTableMetadata()
Returns the metadata of the given type for the given table.
protected abstract mixed getTableMetadata ( $name, $type, $refresh ) | ||
$name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
$type | string |
Metadata type. |
$refresh | boolean |
Whether to reload the table metadata even if it is found in the cache. |
return | mixed |
Metadata. |
---|
abstract protected function getTableMetadata($name, $type, $refresh);
Defined in: yii\db\Schema::getTableNameParts()
Splits full table name into parts
protected array getTableNameParts ( $name ) | ||
$name | string |
protected function getTableNameParts($name)
{
return explode('.', $name);
}
Defined in: yii\db\Schema::getTableNames()
Returns all table names in the database.
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 | boolean |
Whether to fetch the latest available table names. If this is false, table names fetched previously (if available) will be returned. |
return | string[] |
All table names in the database. |
---|
public function getTableNames($schema = '', $refresh = false)
{
if (!isset($this->_tableNames[$schema]) || $refresh) {
$this->_tableNames[$schema] = $this->findTableNames($schema);
}
return $this->_tableNames[$schema];
}
Defined in: yii\db\ConstraintFinderTrait::getTablePrimaryKey()
Obtains the primary key for the named table.
public yii\db\Constraint|null getTablePrimaryKey ( $name, $refresh = false ) | ||
$name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
$refresh | boolean |
Whether to reload the information even if it is found in the cache. |
return | yii\db\Constraint|null |
Table primary key, |
---|
public function getTablePrimaryKey($name, $refresh = false)
{
return $this->getTableMetadata($name, 'primaryKey', $refresh);
}
Defined in: yii\db\Schema::getTableSchema()
Obtains the metadata for the named table.
public yii\db\TableSchema|null getTableSchema ( $name, $refresh = false ) | ||
$name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
$refresh | boolean |
Whether to reload the table schema even if it is found in the cache. |
return | yii\db\TableSchema|null |
Table metadata. |
---|
public function getTableSchema($name, $refresh = false)
{
return $this->getTableMetadata($name, 'schema', $refresh);
}
Defined in: yii\db\Schema::getTableSchemas()
Returns the metadata for all tables in the database.
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 | boolean |
Whether to fetch the latest available table schemas. If this is |
return | yii\db\TableSchema[] |
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);
}
Defined in: yii\db\ConstraintFinderTrait::getTableUniques()
Obtains the unique constraints information for the named table.
public yii\db\Constraint[] getTableUniques ( $name, $refresh = false ) | ||
$name | string |
Table name. The table name may contain schema name if any. Do not quote the table name. |
$refresh | boolean |
Whether to reload the information even if it is found in the cache. |
return | yii\db\Constraint[] |
Table unique constraints. |
---|
public function getTableUniques($name, $refresh = false)
{
return $this->getTableMetadata($name, 'uniques', $refresh);
}
Gets information about given table unique indexes.
protected array getUniqueIndexInformation ( $table ) | ||
$table | yii\db\TableSchema |
The table metadata |
return | array |
With index and column names |
---|
protected function getUniqueIndexInformation($table)
{
$sql = <<<'SQL'
CT
i.relname as indexname,
pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname
(
LECT *, generate_subscripts(indkey, 1) AS k
OM pg_index
x
R JOIN pg_class i ON i.oid = idx.indexrelid
R JOIN pg_class c ON c.oid = idx.indrelid
R JOIN pg_namespace ns ON c.relnamespace = ns.oid
E idx.indisprimary = FALSE AND idx.indisunique = TRUE
c.relname = :tableName AND ns.nspname = :schemaName
R BY i.relname, k
return $this->db->createCommand($sql, [
':schemaName' => $table->schemaName,
':tableName' => $table->name,
])->queryAll();
}
Defined in: yii\db\ViewFinderTrait::getViewNames()
Returns all view names in the database.
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 | boolean |
Whether to fetch the latest available view names. If this is false, view names fetched previously (if available) will be returned. |
return | string[] |
All view names in the database. |
---|
public function getViewNames($schema = '', $refresh = false)
{
if (!isset($this->_viewNames[$schema]) || $refresh) {
$this->_viewNames[$schema] = $this->findViewNames($schema);
}
return $this->_viewNames[$schema];
}
Defined in: yii\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 boolean hasMethod ( $name ) | ||
$name | string |
The method name |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name)
{
return method_exists($this, $name);
}
Defined in: yii\base\BaseObject::hasProperty()
Returns a value indicating whether a property is defined.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
See also:
public boolean hasProperty ( $name, $checkVars = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true)
{
return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}
Defined in: yii\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 void init ( ) |
public function init()
{
}
Executes the INSERT command, returning primary key values.
public array|false insert ( $table, $columns ) | ||
$table | string |
The table that new rows will be inserted into. |
$columns | array |
The column data (name => value) to be inserted into the table. |
return | array|false |
Primary key values or false if the command fails |
---|
public function insert($table, $columns)
{
$params = [];
$sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
$returnColumns = $this->getTableSchema($table)->primaryKey;
if (!empty($returnColumns)) {
$returning = [];
foreach ((array) $returnColumns as $name) {
$returning[] = $this->quoteColumnName($name);
}
$sql .= ' RETURNING ' . implode(', ', $returning);
}
$command = $this->db->createCommand($sql, $params);
$command->prepare(false);
$result = $command->queryOne();
return !$command->pdoStatement->rowCount() ? false : $result;
}
Defined in: yii\db\Schema::isReadQuery()
Returns a value indicating whether a SQL statement is for read purpose.
public boolean isReadQuery ( $sql ) | ||
$sql | string |
The SQL statement |
return | boolean |
Whether a SQL statement is for read purpose. |
---|
public function isReadQuery($sql)
{
$pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
return preg_match($pattern, $sql) > 0;
}
Loads the column information into a yii\db\pgsql\ColumnSchema object.
protected yii\db\pgsql\ColumnSchema loadColumnSchema ( $info ) | ||
$info | array |
Column information |
return | yii\db\pgsql\ColumnSchema |
The column schema object |
---|
protected function loadColumnSchema($info)
{
/** @var ColumnSchema $column */
$column = $this->createColumnSchema();
$column->allowNull = $info['is_nullable'];
$column->autoIncrement = $info['is_autoinc'];
$column->comment = $info['column_comment'];
if ($info['type_scheme'] !== null && !in_array($info['type_scheme'], [$this->defaultSchema, 'pg_catalog'], true)) {
$column->dbType = $info['type_scheme'] . '.' . $info['data_type'];
} else {
$column->dbType = $info['data_type'];
}
$column->defaultValue = $info['column_default'];
$column->enumValues = ($info['enum_values'] !== null) ? explode(',', str_replace(["''"], ["'"], $info['enum_values'])) : null;
$column->unsigned = false; // has no meaning in PG
$column->isPrimaryKey = $info['is_pkey'];
$column->name = $info['column_name'];
$column->precision = $info['numeric_precision'];
$column->scale = $info['numeric_scale'];
$column->size = $info['size'] === null ? null : (int) $info['size'];
$column->dimension = (int) $info['dimension'];
// pg_get_serial_sequence() doesn't track DEFAULT value change. GENERATED BY IDENTITY columns always have null default value
if (isset($column->defaultValue) && preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $column->defaultValue) === 1) {
$column->sequenceName = preg_replace(['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], '', $column->defaultValue);
} elseif (isset($info['sequence_name'])) {
$column->sequenceName = $this->resolveTableName($info['sequence_name'])->fullName;
}
if (isset($this->typeMap[$column->dbType])) {
$column->type = $this->typeMap[$column->dbType];
} else {
$column->type = self::TYPE_STRING;
}
$column->phpType = $this->getColumnPhpType($column);
return $column;
}
protected void loadTableChecks ( $tableName ) | ||
$tableName |
protected function loadTableChecks($tableName)
{
return $this->loadTableConstraints($tableName, 'checks');
}
protected void loadTableDefaultValues ( $tableName ) | ||
$tableName | ||
throws | yii\base\NotSupportedException |
if this method is called. |
---|
protected function loadTableDefaultValues($tableName)
{
throw new NotSupportedException('PostgreSQL does not support default value constraints.');
}
protected void loadTableForeignKeys ( $tableName ) | ||
$tableName |
protected function loadTableForeignKeys($tableName)
{
return $this->loadTableConstraints($tableName, 'foreignKeys');
}
protected void loadTableIndexes ( $tableName ) | ||
$tableName |
protected function loadTableIndexes($tableName)
{
static $sql = <<<'SQL'
CT
"ic"."relname" AS "name",
"ia"."attname" AS "column_name",
"i"."indisunique" AS "index_is_unique",
"i"."indisprimary" AS "index_is_primary"
"pg_class" AS "tc"
R JOIN "pg_namespace" AS "tcns"
ON "tcns"."oid" = "tc"."relnamespace"
R JOIN "pg_index" AS "i"
ON "i"."indrelid" = "tc"."oid"
R JOIN "pg_class" AS "ic"
ON "ic"."oid" = "i"."indexrelid"
R JOIN "pg_attribute" AS "ia"
ON "ia"."attrelid" = "i"."indexrelid"
E "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
R BY "ia"."attnum" 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 void loadTablePrimaryKey ( $tableName ) | ||
$tableName |
protected function loadTablePrimaryKey($tableName)
{
return $this->loadTableConstraints($tableName, 'primaryKey');
}
Loads the metadata for the specified table.
protected yii\db\TableSchema|null loadTableSchema ( $name ) | ||
$name | string |
Table name |
return | yii\db\TableSchema|null |
DBMS-dependent table metadata, |
---|
protected function loadTableSchema($name)
{
$table = new TableSchema();
$this->resolveTableNames($table, $name);
if ($this->findColumns($table)) {
$this->findConstraints($table);
return $table;
}
return null;
}
protected void loadTableUniques ( $tableName ) | ||
$tableName |
protected function loadTableUniques($tableName)
{
return $this->loadTableConstraints($tableName, 'uniques');
}
Defined in: yii\db\Schema::normalizePdoRowKeyCase()
Changes row's array key case to lower if PDO's one is set to uppercase.
protected array normalizePdoRowKeyCase ( array $row, $multiple ) | ||
$row | array |
Row's array or an array of row's arrays. |
$multiple | boolean |
Whether multiple rows or a single row passed. |
return | array |
Normalized row or rows. |
---|
protected function normalizePdoRowKeyCase(array $row, $multiple)
{
if ($this->db->getSlavePdo(true)->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_UPPER) {
return $row;
}
if ($multiple) {
return array_map(function (array $row) {
return array_change_key_case($row, CASE_LOWER);
}, $row);
}
return array_change_key_case($row, CASE_LOWER);
}
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 string quoteColumnName ( $name ) | ||
$name | string |
Column name |
return | string |
The properly quoted column name |
---|
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 string quoteSimpleColumnName ( $name ) | ||
$name | string |
Column name |
return | string |
The properly quoted column name |
---|
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 string quoteSimpleTableName ( $name ) | ||
$name | string |
Table name |
return | string |
The properly quoted table name |
---|
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 string quoteTableName ( $name ) | ||
$name | string |
Table name |
return | string |
The properly quoted table name |
---|
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);
}
Defined in: yii\db\Schema::quoteValue()
Quotes a string value for use in a query.
Note that if the parameter is not a string, it will be returned without change.
See also https://www.php.net/manual/en/function.PDO-quote.php.
public string quoteValue ( $str ) | ||
$str | string |
String to be quoted |
return | string |
The properly quoted string |
---|
public function quoteValue($str)
{
if (!is_string($str)) {
return $str;
}
if (mb_stripos((string)$this->db->dsn, 'odbc:') === false && ($value = $this->db->getSlavePdo(true)->quote($str)) !== false) {
return $value;
}
// the driver doesn't support quote (e.g. oci)
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 void refresh ( ) |
public function refresh()
{
/* @var $cache CacheInterface */
$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 void refreshTableSchema ( $name ) | ||
$name | string |
Table name. |
public function refreshTableSchema($name)
{
$rawName = $this->getRawTableName($name);
unset($this->_tableMetadata[$rawName]);
$this->_tableNames = [];
/* @var $cache CacheInterface */
$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));
}
}
Defined in: yii\db\Schema::releaseSavepoint()
Releases an existing savepoint.
public void releaseSavepoint ( $name ) | ||
$name | string |
The savepoint name |
public function releaseSavepoint($name)
{
$this->db->createCommand("RELEASE SAVEPOINT $name")->execute();
}
Resolves the table name and schema name (if any).
protected yii\db\TableSchema resolveTableName ( $name ) | ||
$name | string |
The table name |
return | yii\db\TableSchema |
yii\db\TableSchema with resolved table, schema, etc. names. |
---|---|---|
throws | yii\base\NotSupportedException |
if this method is not supported by the DBMS. |
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 void resolveTableNames ( $table, $name ) | ||
$table | yii\db\TableSchema |
The table metadata object |
$name | string |
The table name |
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 = $parts[0];
}
$table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
}
Defined in: yii\db\Schema::rollBackSavepoint()
Rolls back to a previously created savepoint.
public void rollBackSavepoint ( $name ) | ||
$name | string |
The savepoint name |
public function rollBackSavepoint($name)
{
$this->db->createCommand("ROLLBACK TO SAVEPOINT $name")->execute();
}
Defined in: yii\db\Schema::setTableMetadata()
Sets the metadata of the given type for the given table.
protected void setTableMetadata ( $name, $type, $data ) | ||
$name | string |
Table name. |
$type | string |
Metadata type. |
$data | mixed |
Metadata. |
protected function setTableMetadata($name, $type, $data)
{
$this->_tableMetadata[$this->getRawTableName($name)][$type] = $data;
}
Defined in: yii\db\Schema::setTransactionIsolationLevel()
Sets the isolation level of the current transaction.
See also https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.
public void setTransactionIsolationLevel ( $level ) | ||
$level | string |
The transaction isolation level to use for this transaction.
This can be one of yii\db\Transaction::READ_UNCOMMITTED, yii\db\Transaction::READ_COMMITTED, yii\db\Transaction::REPEATABLE_READ
and yii\db\Transaction::SERIALIZABLE but also a string containing DBMS specific syntax to be used
after |
public function setTransactionIsolationLevel($level)
{
$this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
}
Defined in: yii\db\Schema::supportsSavepoint()
public boolean supportsSavepoint ( ) | ||
return | boolean |
Whether this DBMS supports savepoint. |
---|
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 string unquoteSimpleColumnName ( $name ) | ||
$name | string |
Column name. |
return | string |
Unquoted column name. |
---|
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 string unquoteSimpleTableName ( $name ) | ||
$name | string |
Table name. |
return | string |
Unquoted table name. |
---|
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);
}
Signup or Login in order to comment.