init
This commit is contained in:
149
vendor/yiisoft/yii2/db/pgsql/ArrayExpressionBuilder.php
vendored
Normal file
149
vendor/yiisoft/yii2/db/pgsql/ArrayExpressionBuilder.php
vendored
Normal file
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\db\pgsql;
|
||||
|
||||
use yii\db\ArrayExpression;
|
||||
use yii\db\ExpressionBuilderInterface;
|
||||
use yii\db\ExpressionBuilderTrait;
|
||||
use yii\db\ExpressionInterface;
|
||||
use yii\db\JsonExpression;
|
||||
use yii\db\Query;
|
||||
|
||||
/**
|
||||
* Class ArrayExpressionBuilder builds [[ArrayExpression]] for PostgreSQL DBMS.
|
||||
*
|
||||
* @author Dmytro Naumenko <d.naumenko.a@gmail.com>
|
||||
* @since 2.0.14
|
||||
*/
|
||||
class ArrayExpressionBuilder implements ExpressionBuilderInterface
|
||||
{
|
||||
use ExpressionBuilderTrait;
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
* @param ArrayExpression|ExpressionInterface $expression the expression to be built
|
||||
*/
|
||||
public function build(ExpressionInterface $expression, array &$params = [])
|
||||
{
|
||||
$value = $expression->getValue();
|
||||
if ($value === null) {
|
||||
return 'NULL';
|
||||
}
|
||||
|
||||
if ($value instanceof Query) {
|
||||
list ($sql, $params) = $this->queryBuilder->build($value, $params);
|
||||
return $this->buildSubqueryArray($sql, $expression);
|
||||
}
|
||||
|
||||
$placeholders = $this->buildPlaceholders($expression, $params);
|
||||
|
||||
return 'ARRAY[' . implode(', ', $placeholders) . ']' . $this->getTypehint($expression);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds placeholders array out of $expression values
|
||||
* @param ExpressionInterface|ArrayExpression $expression
|
||||
* @param array $params the binding parameters.
|
||||
* @return array
|
||||
*/
|
||||
protected function buildPlaceholders(ExpressionInterface $expression, &$params)
|
||||
{
|
||||
$value = $expression->getValue();
|
||||
|
||||
$placeholders = [];
|
||||
if ($value === null || !is_array($value) && !$value instanceof \Traversable) {
|
||||
return $placeholders;
|
||||
}
|
||||
|
||||
if ($expression->getDimension() > 1) {
|
||||
foreach ($value as $item) {
|
||||
$placeholders[] = $this->build($this->unnestArrayExpression($expression, $item), $params);
|
||||
}
|
||||
return $placeholders;
|
||||
}
|
||||
|
||||
foreach ($value as $item) {
|
||||
if ($item instanceof Query) {
|
||||
list ($sql, $params) = $this->queryBuilder->build($item, $params);
|
||||
$placeholders[] = $this->buildSubqueryArray($sql, $expression);
|
||||
continue;
|
||||
}
|
||||
|
||||
$item = $this->typecastValue($expression, $item);
|
||||
if ($item instanceof ExpressionInterface) {
|
||||
$placeholders[] = $this->queryBuilder->buildExpression($item, $params);
|
||||
continue;
|
||||
}
|
||||
|
||||
$placeholders[] = $this->queryBuilder->bindParam($item, $params);
|
||||
}
|
||||
|
||||
return $placeholders;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ArrayExpression $expression
|
||||
* @param mixed $value
|
||||
* @return ArrayExpression
|
||||
*/
|
||||
private function unnestArrayExpression(ArrayExpression $expression, $value)
|
||||
{
|
||||
$expressionClass = get_class($expression);
|
||||
|
||||
return new $expressionClass($value, $expression->getType(), $expression->getDimension()-1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ArrayExpression $expression
|
||||
* @return string the typecast expression based on [[type]].
|
||||
*/
|
||||
protected function getTypehint(ArrayExpression $expression)
|
||||
{
|
||||
if ($expression->getType() === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$result = '::' . $expression->getType();
|
||||
$result .= str_repeat('[]', $expression->getDimension());
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an array expression from a subquery SQL.
|
||||
*
|
||||
* @param string $sql the subquery SQL.
|
||||
* @param ArrayExpression $expression
|
||||
* @return string the subquery array expression.
|
||||
*/
|
||||
protected function buildSubqueryArray($sql, ArrayExpression $expression)
|
||||
{
|
||||
return 'ARRAY(' . $sql . ')' . $this->getTypehint($expression);
|
||||
}
|
||||
|
||||
/**
|
||||
* Casts $value to use in $expression
|
||||
*
|
||||
* @param ArrayExpression $expression
|
||||
* @param mixed $value
|
||||
* @return JsonExpression
|
||||
*/
|
||||
protected function typecastValue(ArrayExpression $expression, $value)
|
||||
{
|
||||
if ($value instanceof ExpressionInterface) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (in_array($expression->getType(), [Schema::TYPE_JSON, Schema::TYPE_JSONB], true)) {
|
||||
return new JsonExpression($value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
109
vendor/yiisoft/yii2/db/pgsql/ArrayParser.php
vendored
Normal file
109
vendor/yiisoft/yii2/db/pgsql/ArrayParser.php
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\db\pgsql;
|
||||
|
||||
/**
|
||||
* The class converts PostgreSQL array representation to PHP array
|
||||
*
|
||||
* @author Sergei Tigrov <rrr-r@ya.ru>
|
||||
* @author Dmytro Naumenko <d.naumenko.a@gmail.com>
|
||||
* @since 2.0.14
|
||||
*/
|
||||
class ArrayParser
|
||||
{
|
||||
/**
|
||||
* @var string Character used in array
|
||||
*/
|
||||
private $delimiter = ',';
|
||||
|
||||
|
||||
/**
|
||||
* Convert array from PostgreSQL to PHP
|
||||
*
|
||||
* @param string $value string to be converted
|
||||
* @return array|null
|
||||
*/
|
||||
public function parse($value)
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($value === '{}') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->parseArray($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pares PgSQL array encoded in string
|
||||
*
|
||||
* @param string $value
|
||||
* @param int $i parse starting position
|
||||
* @return array
|
||||
*/
|
||||
private function parseArray($value, &$i = 0)
|
||||
{
|
||||
$result = [];
|
||||
$len = strlen($value);
|
||||
for (++$i; $i < $len; ++$i) {
|
||||
switch ($value[$i]) {
|
||||
case '{':
|
||||
$result[] = $this->parseArray($value, $i);
|
||||
break;
|
||||
case '}':
|
||||
break 2;
|
||||
case $this->delimiter:
|
||||
if (empty($result)) { // `{}` case
|
||||
$result[] = null;
|
||||
}
|
||||
if (in_array($value[$i + 1], [$this->delimiter, '}'], true)) { // `{,}` case
|
||||
$result[] = null;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
$result[] = $this->parseString($value, $i);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses PgSQL encoded string
|
||||
*
|
||||
* @param string $value
|
||||
* @param int $i parse starting position
|
||||
* @return null|string
|
||||
*/
|
||||
private function parseString($value, &$i)
|
||||
{
|
||||
$isQuoted = $value[$i] === '"';
|
||||
$stringEndChars = $isQuoted ? ['"'] : [$this->delimiter, '}'];
|
||||
$result = '';
|
||||
$len = strlen($value);
|
||||
for ($i += $isQuoted ? 1 : 0; $i < $len; ++$i) {
|
||||
if (in_array($value[$i], ['\\', '"'], true) && in_array($value[$i + 1], [$value[$i], '"'], true)) {
|
||||
++$i;
|
||||
} elseif (in_array($value[$i], $stringEndChars, true)) {
|
||||
break;
|
||||
}
|
||||
|
||||
$result .= $value[$i];
|
||||
}
|
||||
|
||||
$i -= $isQuoted ? 0 : 1;
|
||||
|
||||
if (!$isQuoted && $result === 'NULL') {
|
||||
$result = null;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
152
vendor/yiisoft/yii2/db/pgsql/ColumnSchema.php
vendored
Normal file
152
vendor/yiisoft/yii2/db/pgsql/ColumnSchema.php
vendored
Normal file
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\db\pgsql;
|
||||
|
||||
use yii\db\ArrayExpression;
|
||||
use yii\db\ExpressionInterface;
|
||||
use yii\db\JsonExpression;
|
||||
|
||||
/**
|
||||
* Class ColumnSchema for PostgreSQL database.
|
||||
*
|
||||
* @author Dmytro Naumenko <d.naumenko.a@gmail.com>
|
||||
*/
|
||||
class ColumnSchema extends \yii\db\ColumnSchema
|
||||
{
|
||||
/**
|
||||
* @var int the dimension of array. Defaults to 0, means this column is not an array.
|
||||
*/
|
||||
public $dimension = 0;
|
||||
/**
|
||||
* @var bool whether the column schema should OMIT using JSON support feature.
|
||||
* You can use this property to make upgrade to Yii 2.0.14 easier.
|
||||
* Default to `false`, meaning JSON support is enabled.
|
||||
*
|
||||
* @since 2.0.14.1
|
||||
* @deprecated Since 2.0.14.1 and will be removed in 2.1.
|
||||
*/
|
||||
public $disableJsonSupport = false;
|
||||
/**
|
||||
* @var bool whether the column schema should OMIT using PgSQL Arrays support feature.
|
||||
* You can use this property to make upgrade to Yii 2.0.14 easier.
|
||||
* Default to `false`, meaning Arrays support is enabled.
|
||||
*
|
||||
* @since 2.0.14.1
|
||||
* @deprecated Since 2.0.14.1 and will be removed in 2.1.
|
||||
*/
|
||||
public $disableArraySupport = false;
|
||||
/**
|
||||
* @var bool whether the Array column value should be unserialized to an [[ArrayExpression]] object.
|
||||
* You can use this property to make upgrade to Yii 2.0.14 easier.
|
||||
* Default to `true`, meaning arrays are unserialized to [[ArrayExpression]] objects.
|
||||
*
|
||||
* @since 2.0.14.1
|
||||
* @deprecated Since 2.0.14.1 and will be removed in 2.1.
|
||||
*/
|
||||
public $deserializeArrayColumnToArrayExpression = true;
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function dbTypecast($value)
|
||||
{
|
||||
if ($value === null) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ($value instanceof ExpressionInterface) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ($this->dimension > 0) {
|
||||
return $this->disableArraySupport
|
||||
? (string) $value
|
||||
: new ArrayExpression($value, $this->dbType, $this->dimension);
|
||||
}
|
||||
if (!$this->disableJsonSupport && in_array($this->dbType, [Schema::TYPE_JSON, Schema::TYPE_JSONB], true)) {
|
||||
return new JsonExpression($value, $this->dbType);
|
||||
}
|
||||
|
||||
return $this->typecast($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function phpTypecast($value)
|
||||
{
|
||||
if ($this->dimension > 0) {
|
||||
if ($this->disableArraySupport) {
|
||||
return $value;
|
||||
}
|
||||
if (!is_array($value)) {
|
||||
$value = $this->getArrayParser()->parse($value);
|
||||
}
|
||||
if (is_array($value)) {
|
||||
array_walk_recursive($value, function (&$val, $key) {
|
||||
$val = $this->phpTypecastValue($val);
|
||||
});
|
||||
} elseif ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->deserializeArrayColumnToArrayExpression
|
||||
? new ArrayExpression($value, $this->dbType, $this->dimension)
|
||||
: $value;
|
||||
}
|
||||
|
||||
return $this->phpTypecastValue($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Casts $value after retrieving from the DBMS to PHP representation.
|
||||
*
|
||||
* @param string|null $value
|
||||
* @return bool|mixed|null
|
||||
*/
|
||||
protected function phpTypecastValue($value)
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch ($this->type) {
|
||||
case Schema::TYPE_BOOLEAN:
|
||||
switch (strtolower($value)) {
|
||||
case 't':
|
||||
case 'true':
|
||||
return true;
|
||||
case 'f':
|
||||
case 'false':
|
||||
return false;
|
||||
}
|
||||
return (bool) $value;
|
||||
case Schema::TYPE_JSON:
|
||||
return $this->disableJsonSupport ? $value : json_decode($value, true);
|
||||
}
|
||||
|
||||
return parent::phpTypecast($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates instance of ArrayParser
|
||||
*
|
||||
* @return ArrayParser
|
||||
*/
|
||||
protected function getArrayParser()
|
||||
{
|
||||
static $parser = null;
|
||||
|
||||
if ($parser === null) {
|
||||
$parser = new ArrayParser();
|
||||
}
|
||||
|
||||
return $parser;
|
||||
}
|
||||
}
|
||||
62
vendor/yiisoft/yii2/db/pgsql/JsonExpressionBuilder.php
vendored
Normal file
62
vendor/yiisoft/yii2/db/pgsql/JsonExpressionBuilder.php
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\db\pgsql;
|
||||
|
||||
use yii\db\ArrayExpression;
|
||||
use yii\db\ExpressionBuilderInterface;
|
||||
use yii\db\ExpressionBuilderTrait;
|
||||
use yii\db\ExpressionInterface;
|
||||
use yii\db\JsonExpression;
|
||||
use yii\db\Query;
|
||||
use yii\helpers\Json;
|
||||
|
||||
/**
|
||||
* Class JsonExpressionBuilder builds [[JsonExpression]] for PostgreSQL DBMS.
|
||||
*
|
||||
* @author Dmytro Naumenko <d.naumenko.a@gmail.com>
|
||||
* @since 2.0.14
|
||||
*/
|
||||
class JsonExpressionBuilder implements ExpressionBuilderInterface
|
||||
{
|
||||
use ExpressionBuilderTrait;
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
* @param JsonExpression|ExpressionInterface $expression the expression to be built
|
||||
*/
|
||||
public function build(ExpressionInterface $expression, array &$params = [])
|
||||
{
|
||||
$value = $expression->getValue();
|
||||
|
||||
if ($value instanceof Query) {
|
||||
list ($sql, $params) = $this->queryBuilder->build($value, $params);
|
||||
return "($sql)" . $this->getTypecast($expression);
|
||||
}
|
||||
if ($value instanceof ArrayExpression) {
|
||||
$placeholder = 'array_to_json(' . $this->queryBuilder->buildExpression($value, $params) . ')';
|
||||
} else {
|
||||
$placeholder = $this->queryBuilder->bindParam(Json::encode($value), $params);
|
||||
}
|
||||
|
||||
return $placeholder . $this->getTypecast($expression);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param JsonExpression $expression
|
||||
* @return string the typecast expression based on [[type]].
|
||||
*/
|
||||
protected function getTypecast(JsonExpression $expression)
|
||||
{
|
||||
if ($expression->getType() === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return '::' . $expression->getType();
|
||||
}
|
||||
}
|
||||
480
vendor/yiisoft/yii2/db/pgsql/QueryBuilder.php
vendored
Normal file
480
vendor/yiisoft/yii2/db/pgsql/QueryBuilder.php
vendored
Normal file
@@ -0,0 +1,480 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\db\pgsql;
|
||||
|
||||
use yii\base\InvalidArgumentException;
|
||||
use yii\db\Constraint;
|
||||
use yii\db\Expression;
|
||||
use yii\db\ExpressionInterface;
|
||||
use yii\db\Query;
|
||||
use yii\db\PdoValue;
|
||||
use yii\helpers\StringHelper;
|
||||
|
||||
/**
|
||||
* QueryBuilder is the query builder for PostgreSQL databases.
|
||||
*
|
||||
* @author Gevik Babakhani <gevikb@gmail.com>
|
||||
* @since 2.0
|
||||
*/
|
||||
class QueryBuilder extends \yii\db\QueryBuilder
|
||||
{
|
||||
/**
|
||||
* Defines a UNIQUE index for [[createIndex()]].
|
||||
* @since 2.0.6
|
||||
*/
|
||||
const INDEX_UNIQUE = 'unique';
|
||||
/**
|
||||
* Defines a B-tree index for [[createIndex()]].
|
||||
* @since 2.0.6
|
||||
*/
|
||||
const INDEX_B_TREE = 'btree';
|
||||
/**
|
||||
* Defines a hash index for [[createIndex()]].
|
||||
* @since 2.0.6
|
||||
*/
|
||||
const INDEX_HASH = 'hash';
|
||||
/**
|
||||
* Defines a GiST index for [[createIndex()]].
|
||||
* @since 2.0.6
|
||||
*/
|
||||
const INDEX_GIST = 'gist';
|
||||
/**
|
||||
* Defines a GIN index for [[createIndex()]].
|
||||
* @since 2.0.6
|
||||
*/
|
||||
const INDEX_GIN = 'gin';
|
||||
|
||||
/**
|
||||
* @var array mapping from abstract column types (keys) to physical column types (values).
|
||||
*/
|
||||
public $typeMap = [
|
||||
Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
|
||||
Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
|
||||
Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
|
||||
Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
|
||||
Schema::TYPE_CHAR => 'char(1)',
|
||||
Schema::TYPE_STRING => 'varchar(255)',
|
||||
Schema::TYPE_TEXT => 'text',
|
||||
Schema::TYPE_TINYINT => 'smallint',
|
||||
Schema::TYPE_SMALLINT => 'smallint',
|
||||
Schema::TYPE_INTEGER => 'integer',
|
||||
Schema::TYPE_BIGINT => 'bigint',
|
||||
Schema::TYPE_FLOAT => 'double precision',
|
||||
Schema::TYPE_DOUBLE => 'double precision',
|
||||
Schema::TYPE_DECIMAL => 'numeric(10,0)',
|
||||
Schema::TYPE_DATETIME => 'timestamp(0)',
|
||||
Schema::TYPE_TIMESTAMP => 'timestamp(0)',
|
||||
Schema::TYPE_TIME => 'time(0)',
|
||||
Schema::TYPE_DATE => 'date',
|
||||
Schema::TYPE_BINARY => 'bytea',
|
||||
Schema::TYPE_BOOLEAN => 'boolean',
|
||||
Schema::TYPE_MONEY => 'numeric(19,4)',
|
||||
Schema::TYPE_JSON => 'jsonb',
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function defaultConditionClasses()
|
||||
{
|
||||
return array_merge(parent::defaultConditionClasses(), [
|
||||
'ILIKE' => 'yii\db\conditions\LikeCondition',
|
||||
'NOT ILIKE' => 'yii\db\conditions\LikeCondition',
|
||||
'OR ILIKE' => 'yii\db\conditions\LikeCondition',
|
||||
'OR NOT ILIKE' => 'yii\db\conditions\LikeCondition',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function defaultExpressionBuilders()
|
||||
{
|
||||
return array_merge(parent::defaultExpressionBuilders(), [
|
||||
'yii\db\ArrayExpression' => 'yii\db\pgsql\ArrayExpressionBuilder',
|
||||
'yii\db\JsonExpression' => 'yii\db\pgsql\JsonExpressionBuilder',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for creating a new index.
|
||||
* @param string $name the name of the index. The name will be properly quoted by the method.
|
||||
* @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
|
||||
* @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
|
||||
* separate them with commas or use an array to represent them. Each column name will be properly quoted
|
||||
* by the method, unless a parenthesis is found in the name.
|
||||
* @param bool|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or [[INDEX_UNIQUE]] to create
|
||||
* a unique index, `false` to make a non-unique index using the default index type, or one of the following constants to specify
|
||||
* the index method to use: [[INDEX_B_TREE]], [[INDEX_HASH]], [[INDEX_GIST]], [[INDEX_GIN]].
|
||||
* @return string the SQL statement for creating a new index.
|
||||
* @see http://www.postgresql.org/docs/8.2/static/sql-createindex.html
|
||||
*/
|
||||
public function createIndex($name, $table, $columns, $unique = false)
|
||||
{
|
||||
if ($unique === self::INDEX_UNIQUE || $unique === true) {
|
||||
$index = false;
|
||||
$unique = true;
|
||||
} else {
|
||||
$index = $unique;
|
||||
$unique = false;
|
||||
}
|
||||
|
||||
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') .
|
||||
$this->db->quoteTableName($name) . ' ON ' .
|
||||
$this->db->quoteTableName($table) .
|
||||
($index !== false ? " USING $index" : '') .
|
||||
' (' . $this->buildColumns($columns) . ')';
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for dropping an index.
|
||||
* @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
|
||||
* @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
|
||||
* @return string the SQL statement for dropping an index.
|
||||
*/
|
||||
public function dropIndex($name, $table)
|
||||
{
|
||||
return 'DROP INDEX ' . $this->db->quoteTableName($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for renaming a DB table.
|
||||
* @param string $oldName the table to be renamed. The name will be properly quoted by the method.
|
||||
* @param string $newName the new table name. The name will be properly quoted by the method.
|
||||
* @return string the SQL statement for renaming a DB table.
|
||||
*/
|
||||
public function renameTable($oldName, $newName)
|
||||
{
|
||||
return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SQL statement for resetting the sequence value of a table's primary key.
|
||||
* The sequence will be reset such that the primary key of the next new row inserted
|
||||
* will have the specified value or 1.
|
||||
* @param string $tableName the name of the table whose primary key sequence will be reset
|
||||
* @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
|
||||
* the next new row's primary key will have a value 1.
|
||||
* @return string the SQL statement for resetting sequence
|
||||
* @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
|
||||
*/
|
||||
public function resetSequence($tableName, $value = null)
|
||||
{
|
||||
$table = $this->db->getTableSchema($tableName);
|
||||
if ($table !== null && $table->sequenceName !== null) {
|
||||
// c.f. http://www.postgresql.org/docs/8.1/static/functions-sequence.html
|
||||
$sequence = $this->db->quoteTableName($table->sequenceName);
|
||||
$tableName = $this->db->quoteTableName($tableName);
|
||||
if ($value === null) {
|
||||
$key = $this->db->quoteColumnName(reset($table->primaryKey));
|
||||
$value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
|
||||
} else {
|
||||
$value = (int) $value;
|
||||
}
|
||||
|
||||
return "SELECT SETVAL('$sequence',$value,false)";
|
||||
} elseif ($table === null) {
|
||||
throw new InvalidArgumentException("Table not found: $tableName");
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for enabling or disabling integrity check.
|
||||
* @param bool $check whether to turn on or off the integrity check.
|
||||
* @param string $schema the schema of the tables.
|
||||
* @param string $table the table name.
|
||||
* @return string the SQL statement for checking integrity
|
||||
*/
|
||||
public function checkIntegrity($check = true, $schema = '', $table = '')
|
||||
{
|
||||
$enable = $check ? 'ENABLE' : 'DISABLE';
|
||||
$schema = $schema ?: $this->db->getSchema()->defaultSchema;
|
||||
$tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
|
||||
$viewNames = $this->db->getSchema()->getViewNames($schema);
|
||||
$tableNames = array_diff($tableNames, $viewNames);
|
||||
$command = '';
|
||||
|
||||
foreach ($tableNames as $tableName) {
|
||||
$tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
|
||||
$command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
|
||||
}
|
||||
|
||||
// enable to have ability to alter several tables
|
||||
$this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
|
||||
|
||||
return $command;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for truncating a DB table.
|
||||
* Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
|
||||
* @param string $table the table to be truncated. The name will be properly quoted by the method.
|
||||
* @return string the SQL statement for truncating a DB table.
|
||||
*/
|
||||
public function truncateTable($table)
|
||||
{
|
||||
return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a SQL statement for changing the definition of a column.
|
||||
* @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
|
||||
* @param string $column the name of the column to be changed. The name will be properly quoted by the method.
|
||||
* @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
|
||||
* column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
|
||||
* in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
|
||||
* will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
|
||||
* @return string the SQL statement for changing the definition of a column.
|
||||
*/
|
||||
public function alterColumn($table, $column, $type)
|
||||
{
|
||||
// https://github.com/yiisoft/yii2/issues/4492
|
||||
// http://www.postgresql.org/docs/9.1/static/sql-altertable.html
|
||||
if (!preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
|
||||
$type = 'TYPE ' . $this->getColumnType($type);
|
||||
}
|
||||
|
||||
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ALTER COLUMN '
|
||||
. $this->db->quoteColumnName($column) . ' ' . $type;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function insert($table, $columns, &$params)
|
||||
{
|
||||
return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
* @see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT
|
||||
* @see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291
|
||||
*/
|
||||
public function upsert($table, $insertColumns, $updateColumns, &$params)
|
||||
{
|
||||
$insertColumns = $this->normalizeTableRowData($table, $insertColumns);
|
||||
if (!is_bool($updateColumns)) {
|
||||
$updateColumns = $this->normalizeTableRowData($table, $updateColumns);
|
||||
}
|
||||
if (version_compare($this->db->getServerVersion(), '9.5', '<')) {
|
||||
return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
|
||||
}
|
||||
|
||||
return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* [[upsert()]] implementation for PostgreSQL 9.5 or higher.
|
||||
* @param string $table
|
||||
* @param array|Query $insertColumns
|
||||
* @param array|bool $updateColumns
|
||||
* @param array $params
|
||||
* @return string
|
||||
*/
|
||||
private function newUpsert($table, $insertColumns, $updateColumns, &$params)
|
||||
{
|
||||
$insertSql = $this->insert($table, $insertColumns, $params);
|
||||
list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
|
||||
if (empty($uniqueNames)) {
|
||||
return $insertSql;
|
||||
}
|
||||
|
||||
if ($updateColumns === false) {
|
||||
return "$insertSql ON CONFLICT DO NOTHING";
|
||||
}
|
||||
|
||||
if ($updateColumns === true) {
|
||||
$updateColumns = [];
|
||||
foreach ($updateNames as $name) {
|
||||
$updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name));
|
||||
}
|
||||
}
|
||||
list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
|
||||
return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET ' . implode(', ', $updates);
|
||||
}
|
||||
|
||||
/**
|
||||
* [[upsert()]] implementation for PostgreSQL older than 9.5.
|
||||
* @param string $table
|
||||
* @param array|Query $insertColumns
|
||||
* @param array|bool $updateColumns
|
||||
* @param array $params
|
||||
* @return string
|
||||
*/
|
||||
private function oldUpsert($table, $insertColumns, $updateColumns, &$params)
|
||||
{
|
||||
/** @var Constraint[] $constraints */
|
||||
list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
|
||||
if (empty($uniqueNames)) {
|
||||
return $this->insert($table, $insertColumns, $params);
|
||||
}
|
||||
|
||||
/** @var Schema $schema */
|
||||
$schema = $this->db->getSchema();
|
||||
if (!$insertColumns instanceof Query) {
|
||||
$tableSchema = $schema->getTableSchema($table);
|
||||
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
|
||||
foreach ($insertColumns as $name => $value) {
|
||||
// NULLs and numeric values must be type hinted in order to be used in SET assigments
|
||||
// NVM, let's cast them all
|
||||
if (isset($columnSchemas[$name])) {
|
||||
$phName = self::PARAM_PREFIX . count($params);
|
||||
$params[$phName] = $value;
|
||||
$insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})");
|
||||
}
|
||||
}
|
||||
}
|
||||
list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
|
||||
$updateCondition = ['or'];
|
||||
$insertCondition = ['or'];
|
||||
$quotedTableName = $schema->quoteTableName($table);
|
||||
foreach ($constraints as $constraint) {
|
||||
$constraintUpdateCondition = ['and'];
|
||||
$constraintInsertCondition = ['and'];
|
||||
foreach ($constraint->columnNames as $name) {
|
||||
$quotedName = $schema->quoteColumnName($name);
|
||||
$constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
|
||||
$constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName";
|
||||
}
|
||||
$updateCondition[] = $constraintUpdateCondition;
|
||||
$insertCondition[] = $constraintInsertCondition;
|
||||
}
|
||||
$withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames)
|
||||
. ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')';
|
||||
if ($updateColumns === false) {
|
||||
$selectSubQuery = (new Query())
|
||||
->select(new Expression('1'))
|
||||
->from($table)
|
||||
->where($updateCondition);
|
||||
$insertSelectSubQuery = (new Query())
|
||||
->select($insertNames)
|
||||
->from('EXCLUDED')
|
||||
->where(['not exists', $selectSubQuery]);
|
||||
$insertSql = $this->insert($table, $insertSelectSubQuery, $params);
|
||||
return "$withSql $insertSql";
|
||||
}
|
||||
|
||||
if ($updateColumns === true) {
|
||||
$updateColumns = [];
|
||||
foreach ($updateNames as $name) {
|
||||
$quotedName = $this->db->quoteColumnName($name);
|
||||
if (strrpos($quotedName, '.') === false) {
|
||||
$quotedName = '"EXCLUDED".' . $quotedName;
|
||||
}
|
||||
$updateColumns[$name] = new Expression($quotedName);
|
||||
}
|
||||
}
|
||||
list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
|
||||
$updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates)
|
||||
. ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params)
|
||||
. ' RETURNING ' . $this->db->quoteTableName($table) .'.*';
|
||||
$selectUpsertSubQuery = (new Query())
|
||||
->select(new Expression('1'))
|
||||
->from('upsert')
|
||||
->where($insertCondition);
|
||||
$insertSelectSubQuery = (new Query())
|
||||
->select($insertNames)
|
||||
->from('EXCLUDED')
|
||||
->where(['not exists', $selectUpsertSubQuery]);
|
||||
$insertSql = $this->insert($table, $insertSelectSubQuery, $params);
|
||||
return "$withSql, \"upsert\" AS ($updateSql) $insertSql";
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function update($table, $columns, $condition, &$params)
|
||||
{
|
||||
return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
|
||||
*
|
||||
* @param string $table the table that data will be saved into.
|
||||
* @param array|Query $columns the column data (name => value) to be saved into the table or instance
|
||||
* of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
|
||||
* Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
|
||||
* @return array normalized columns
|
||||
* @since 2.0.9
|
||||
*/
|
||||
private function normalizeTableRowData($table, $columns)
|
||||
{
|
||||
if ($columns instanceof Query) {
|
||||
return $columns;
|
||||
}
|
||||
|
||||
if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
|
||||
$columnSchemas = $tableSchema->columns;
|
||||
foreach ($columns as $name => $value) {
|
||||
if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) {
|
||||
$columns[$name] = new PdoValue($value, \PDO::PARAM_LOB); // explicitly setup PDO param type for binary column
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function batchInsert($table, $columns, $rows, &$params = [])
|
||||
{
|
||||
if (empty($rows)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$schema = $this->db->getSchema();
|
||||
if (($tableSchema = $schema->getTableSchema($table)) !== null) {
|
||||
$columnSchemas = $tableSchema->columns;
|
||||
} else {
|
||||
$columnSchemas = [];
|
||||
}
|
||||
|
||||
$values = [];
|
||||
foreach ($rows as $row) {
|
||||
$vs = [];
|
||||
foreach ($row as $i => $value) {
|
||||
if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
|
||||
$value = $columnSchemas[$columns[$i]]->dbTypecast($value);
|
||||
}
|
||||
if (is_string($value)) {
|
||||
$value = $schema->quoteValue($value);
|
||||
} elseif (is_float($value)) {
|
||||
// ensure type cast always has . as decimal separator in all locales
|
||||
$value = StringHelper::floatToString($value);
|
||||
} elseif ($value === true) {
|
||||
$value = 'TRUE';
|
||||
} elseif ($value === false) {
|
||||
$value = 'FALSE';
|
||||
} elseif ($value === null) {
|
||||
$value = 'NULL';
|
||||
} elseif ($value instanceof ExpressionInterface) {
|
||||
$value = $this->buildExpression($value, $params);
|
||||
}
|
||||
$vs[] = $value;
|
||||
}
|
||||
$values[] = '(' . implode(', ', $vs) . ')';
|
||||
}
|
||||
if (empty($values)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
foreach ($columns as $i => $name) {
|
||||
$columns[$i] = $schema->quoteColumnName($name);
|
||||
}
|
||||
|
||||
return 'INSERT INTO ' . $schema->quoteTableName($table)
|
||||
. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
|
||||
}
|
||||
}
|
||||
724
vendor/yiisoft/yii2/db/pgsql/Schema.php
vendored
Normal file
724
vendor/yiisoft/yii2/db/pgsql/Schema.php
vendored
Normal file
@@ -0,0 +1,724 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://www.yiiframework.com/
|
||||
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||
* @license http://www.yiiframework.com/license/
|
||||
*/
|
||||
|
||||
namespace yii\db\pgsql;
|
||||
|
||||
use yii\base\NotSupportedException;
|
||||
use yii\db\CheckConstraint;
|
||||
use yii\db\Constraint;
|
||||
use yii\db\ConstraintFinderInterface;
|
||||
use yii\db\ConstraintFinderTrait;
|
||||
use yii\db\Expression;
|
||||
use yii\db\ForeignKeyConstraint;
|
||||
use yii\db\IndexConstraint;
|
||||
use yii\db\TableSchema;
|
||||
use yii\db\ViewFinderTrait;
|
||||
use yii\helpers\ArrayHelper;
|
||||
|
||||
/**
|
||||
* Schema is the class for retrieving metadata from a PostgreSQL database
|
||||
* (version 9.x and above).
|
||||
*
|
||||
* @author Gevik Babakhani <gevikb@gmail.com>
|
||||
* @since 2.0
|
||||
*/
|
||||
class Schema extends \yii\db\Schema implements ConstraintFinderInterface
|
||||
{
|
||||
use ViewFinderTrait;
|
||||
use ConstraintFinderTrait;
|
||||
|
||||
const TYPE_JSONB = 'jsonb';
|
||||
|
||||
/**
|
||||
* @var string the default schema used for the current session.
|
||||
*/
|
||||
public $defaultSchema = 'public';
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public $columnSchemaClass = 'yii\db\pgsql\ColumnSchema';
|
||||
/**
|
||||
* @var array mapping from physical column types (keys) to abstract
|
||||
* column types (values)
|
||||
* @see http://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-TABLE
|
||||
*/
|
||||
public $typeMap = [
|
||||
'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, // should not be used. it's pg internal!
|
||||
|
||||
'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,
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $tableQuoteCharacter = '"';
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function findSchemaNames()
|
||||
{
|
||||
static $sql = <<<'SQL'
|
||||
SELECT "ns"."nspname"
|
||||
FROM "pg_namespace" AS "ns"
|
||||
WHERE "ns"."nspname" != 'information_schema' AND "ns"."nspname" NOT LIKE 'pg_%'
|
||||
ORDER BY "ns"."nspname" ASC
|
||||
SQL;
|
||||
|
||||
return $this->db->createCommand($sql)->queryColumn();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function findTableNames($schema = '')
|
||||
{
|
||||
if ($schema === '') {
|
||||
$schema = $this->defaultSchema;
|
||||
}
|
||||
$sql = <<<'SQL'
|
||||
SELECT c.relname AS table_name
|
||||
FROM pg_class c
|
||||
INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
|
||||
WHERE ns.nspname = :schemaName AND c.relkind IN ('r','v','m','f')
|
||||
ORDER BY c.relname
|
||||
SQL;
|
||||
return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function loadTableSchema($name)
|
||||
{
|
||||
$table = new TableSchema();
|
||||
$this->resolveTableNames($table, $name);
|
||||
if ($this->findColumns($table)) {
|
||||
$this->findConstraints($table);
|
||||
return $table;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function loadTablePrimaryKey($tableName)
|
||||
{
|
||||
return $this->loadTableConstraints($tableName, 'primaryKey');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function loadTableForeignKeys($tableName)
|
||||
{
|
||||
return $this->loadTableConstraints($tableName, 'foreignKeys');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function loadTableIndexes($tableName)
|
||||
{
|
||||
static $sql = <<<'SQL'
|
||||
SELECT
|
||||
"ic"."relname" AS "name",
|
||||
"ia"."attname" AS "column_name",
|
||||
"i"."indisunique" AS "index_is_unique",
|
||||
"i"."indisprimary" AS "index_is_primary"
|
||||
FROM "pg_class" AS "tc"
|
||||
INNER JOIN "pg_namespace" AS "tcns"
|
||||
ON "tcns"."oid" = "tc"."relnamespace"
|
||||
INNER JOIN "pg_index" AS "i"
|
||||
ON "i"."indrelid" = "tc"."oid"
|
||||
INNER JOIN "pg_class" AS "ic"
|
||||
ON "ic"."oid" = "i"."indexrelid"
|
||||
INNER JOIN "pg_attribute" AS "ia"
|
||||
ON "ia"."attrelid" = "i"."indrelid" AND "ia"."attnum" = ANY ("i"."indkey")
|
||||
WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
|
||||
ORDER BY "ia"."attnum" ASC
|
||||
SQL;
|
||||
|
||||
$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;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function loadTableUniques($tableName)
|
||||
{
|
||||
return $this->loadTableConstraints($tableName, 'uniques');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function loadTableChecks($tableName)
|
||||
{
|
||||
return $this->loadTableConstraints($tableName, 'checks');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
* @throws NotSupportedException if this method is called.
|
||||
*/
|
||||
protected function loadTableDefaultValues($tableName)
|
||||
{
|
||||
throw new NotSupportedException('PostgreSQL does not support default value constraints.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a query builder for the PostgreSQL database.
|
||||
* @return QueryBuilder query builder instance
|
||||
*/
|
||||
public function createQueryBuilder()
|
||||
{
|
||||
return new QueryBuilder($this->db);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the table name and schema name (if any).
|
||||
* @param TableSchema $table the table metadata object
|
||||
* @param string $name 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc]
|
||||
*/
|
||||
protected function findViewNames($schema = '')
|
||||
{
|
||||
if ($schema === '') {
|
||||
$schema = $this->defaultSchema;
|
||||
}
|
||||
$sql = <<<'SQL'
|
||||
SELECT c.relname AS table_name
|
||||
FROM pg_class c
|
||||
INNER JOIN pg_namespace ns ON ns.oid = c.relnamespace
|
||||
WHERE ns.nspname = :schemaName AND (c.relkind = 'v' OR c.relkind = 'm')
|
||||
ORDER BY c.relname
|
||||
SQL;
|
||||
return $this->db->createCommand($sql, [':schemaName' => $schema])->queryColumn();
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the foreign key column details for the given table.
|
||||
* @param TableSchema $table 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:
|
||||
//http://www.postgresql.org/message-id/26677.1086673982@sss.pgh.pa.us
|
||||
|
||||
$sql = <<<SQL
|
||||
select
|
||||
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
|
||||
from
|
||||
(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]
|
||||
where
|
||||
ct.contype='f'
|
||||
and c.relname={$tableName}
|
||||
and ns.nspname={$tableSchema}
|
||||
order by
|
||||
fns.nspname, fc.relname, a.attnum
|
||||
SQL;
|
||||
|
||||
$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']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets information about given table unique indexes.
|
||||
* @param TableSchema $table the table metadata
|
||||
* @return array with index and column names
|
||||
*/
|
||||
protected function getUniqueIndexInformation($table)
|
||||
{
|
||||
$sql = <<<'SQL'
|
||||
SELECT
|
||||
i.relname as indexname,
|
||||
pg_get_indexdef(idx.indexrelid, k + 1, TRUE) AS columnname
|
||||
FROM (
|
||||
SELECT *, generate_subscripts(indkey, 1) AS k
|
||||
FROM pg_index
|
||||
) idx
|
||||
INNER JOIN pg_class i ON i.oid = idx.indexrelid
|
||||
INNER JOIN pg_class c ON c.oid = idx.indrelid
|
||||
INNER JOIN pg_namespace ns ON c.relnamespace = ns.oid
|
||||
WHERE idx.indisprimary = FALSE AND idx.indisunique = TRUE
|
||||
AND c.relname = :tableName AND ns.nspname = :schemaName
|
||||
ORDER BY i.relname, k
|
||||
SQL;
|
||||
|
||||
return $this->db->createCommand($sql, [
|
||||
':schemaName' => $table->schemaName,
|
||||
':tableName' => $table->name,
|
||||
])->queryAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all unique indexes for the given table.
|
||||
*
|
||||
* Each array element is of the following structure:
|
||||
*
|
||||
* ```php
|
||||
* [
|
||||
* 'IndexName1' => ['col1' [, ...]],
|
||||
* 'IndexName2' => ['col2' [, ...]],
|
||||
* ]
|
||||
* ```
|
||||
*
|
||||
* @param TableSchema $table 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 (!empty($column) && $column[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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the metadata of table columns.
|
||||
* @param TableSchema $table the table metadata
|
||||
* @return bool whether the table exists in the database
|
||||
*/
|
||||
protected function findColumns($table)
|
||||
{
|
||||
$tableName = $this->db->quoteValue($table->name);
|
||||
$schemaName = $this->db->quoteValue($table->schemaName);
|
||||
$sql = <<<SQL
|
||||
SELECT
|
||||
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,
|
||||
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) AS is_autoinc,
|
||||
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
|
||||
FROM
|
||||
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'
|
||||
WHERE
|
||||
a.attnum > 0 AND t.typname != ''
|
||||
AND c.relname = {$tableName}
|
||||
AND d.nspname = {$schemaName}
|
||||
ORDER BY
|
||||
a.attnum;
|
||||
SQL;
|
||||
$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 && preg_match("/nextval\\('\"?\\w+\"?\.?\"?\\w+\"?'(::regclass)?\\)/", $column->defaultValue) === 1) {
|
||||
$table->sequenceName = preg_replace(['/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'], '', $column->defaultValue);
|
||||
}
|
||||
$column->defaultValue = null;
|
||||
} elseif ($column->defaultValue) {
|
||||
if ($column->type === 'timestamp' && $column->defaultValue === 'now()') {
|
||||
$column->defaultValue = new Expression($column->defaultValue);
|
||||
} elseif ($column->type === 'boolean') {
|
||||
$column->defaultValue = ($column->defaultValue === 'true');
|
||||
} elseif (strncasecmp($column->dbType, 'bit', 3) === 0 || strncasecmp($column->dbType, 'varbit', 6) === 0) {
|
||||
$column->defaultValue = bindec(trim($column->defaultValue, 'B\''));
|
||||
} 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the column information into a [[ColumnSchema]] object.
|
||||
* @param array $info column information
|
||||
* @return 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'];
|
||||
$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'];
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads multiple types of constraints and returns the specified ones.
|
||||
* @param string $tableName table name.
|
||||
* @param string $returnType return type:
|
||||
* - primaryKey
|
||||
* - foreignKeys
|
||||
* - uniques
|
||||
* - checks
|
||||
* @return mixed constraints.
|
||||
*/
|
||||
private function loadTableConstraints($tableName, $returnType)
|
||||
{
|
||||
static $sql = <<<'SQL'
|
||||
SELECT
|
||||
"c"."conname" AS "name",
|
||||
"a"."attname" AS "column_name",
|
||||
"c"."contype" AS "type",
|
||||
"ftcns"."nspname" AS "foreign_table_schema",
|
||||
"ftc"."relname" AS "foreign_table_name",
|
||||
"fa"."attname" AS "foreign_column_name",
|
||||
"c"."confupdtype" AS "on_update",
|
||||
"c"."confdeltype" AS "on_delete",
|
||||
"c"."consrc" AS "check_expr"
|
||||
FROM "pg_class" AS "tc"
|
||||
INNER JOIN "pg_namespace" AS "tcns"
|
||||
ON "tcns"."oid" = "tc"."relnamespace"
|
||||
INNER JOIN "pg_constraint" AS "c"
|
||||
ON "c"."conrelid" = "tc"."oid"
|
||||
INNER JOIN "pg_attribute" AS "a"
|
||||
ON "a"."attrelid" = "c"."conrelid" AND "a"."attnum" = ANY ("c"."conkey")
|
||||
LEFT JOIN "pg_class" AS "ftc"
|
||||
ON "ftc"."oid" = "c"."confrelid"
|
||||
LEFT JOIN "pg_namespace" AS "ftcns"
|
||||
ON "ftcns"."oid" = "ftc"."relnamespace"
|
||||
LEFT JOIN "pg_attribute" "fa"
|
||||
ON "fa"."attrelid" = "c"."confrelid" AND "fa"."attnum" = ANY ("c"."confkey")
|
||||
WHERE "tcns"."nspname" = :schemaName AND "tc"."relname" = :tableName
|
||||
ORDER BY "a"."attnum" ASC, "fa"."attnum" ASC
|
||||
SQL;
|
||||
static $actionTypes = [
|
||||
'a' => 'NO ACTION',
|
||||
'r' => 'RESTRICT',
|
||||
'c' => 'CASCADE',
|
||||
'n' => 'SET NULL',
|
||||
'd' => 'SET DEFAULT',
|
||||
];
|
||||
|
||||
$resolvedName = $this->resolveTableName($tableName);
|
||||
$constraints = $this->db->createCommand($sql, [
|
||||
':schemaName' => $resolvedName->schemaName,
|
||||
':tableName' => $resolvedName->name,
|
||||
])->queryAll();
|
||||
$constraints = $this->normalizePdoRowKeyCase($constraints, true);
|
||||
$constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
|
||||
$result = [
|
||||
'primaryKey' => null,
|
||||
'foreignKeys' => [],
|
||||
'uniques' => [],
|
||||
'checks' => [],
|
||||
];
|
||||
foreach ($constraints as $type => $names) {
|
||||
foreach ($names as $name => $constraint) {
|
||||
switch ($type) {
|
||||
case 'p':
|
||||
$result['primaryKey'] = new Constraint([
|
||||
'name' => $name,
|
||||
'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
|
||||
]);
|
||||
break;
|
||||
case 'f':
|
||||
$result['foreignKeys'][] = new ForeignKeyConstraint([
|
||||
'name' => $name,
|
||||
'columnNames' => array_keys(array_count_values(ArrayHelper::getColumn($constraint, 'column_name'))),
|
||||
'foreignSchemaName' => $constraint[0]['foreign_table_schema'],
|
||||
'foreignTableName' => $constraint[0]['foreign_table_name'],
|
||||
'foreignColumnNames' => array_keys(array_count_values(ArrayHelper::getColumn($constraint, 'foreign_column_name'))),
|
||||
'onDelete' => isset($actionTypes[$constraint[0]['on_delete']]) ? $actionTypes[$constraint[0]['on_delete']] : null,
|
||||
'onUpdate' => isset($actionTypes[$constraint[0]['on_update']]) ? $actionTypes[$constraint[0]['on_update']] : null,
|
||||
]);
|
||||
break;
|
||||
case 'u':
|
||||
$result['uniques'][] = new Constraint([
|
||||
'name' => $name,
|
||||
'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
|
||||
]);
|
||||
break;
|
||||
case 'c':
|
||||
$result['checks'][] = new CheckConstraint([
|
||||
'name' => $name,
|
||||
'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
|
||||
'expression' => $constraint[0]['check_expr'],
|
||||
]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($result as $type => $data) {
|
||||
$this->setTableMetadata($tableName, $type, $data);
|
||||
}
|
||||
|
||||
return $result[$returnType];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user