Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PostgreSQL load indexes without column ordering #16639

Open
carono opened this issue Aug 14, 2018 · 4 comments
Open

PostgreSQL load indexes without column ordering #16639

carono opened this issue Aug 14, 2018 · 4 comments

Comments

@carono
Copy link
Contributor

carono commented Aug 14, 2018

The function \yii\db\pgsql\Schema::loadTableIndexes returns all table indexes, but without the original column sequence

Функция \yii\db\pgsql\Schema::loadTableIndexes возвращает все индексы таблицы, но без изначальной последовательности столбцов

What steps will reproduce the problem?

We create a migration with 2 indices on the same columns, but with different order
Создаем миграцию с 2мя индексами на одни и те же столбцы, но с разной очередностью

$this->createIndex('name-login-idx', 'user', ['name', 'login']);
$this->createIndex('login-name-idx', 'user', ['login', 'name']);
$db = Yii::$app->db;
$reflectionMethod = new \ReflectionMethod(get_class($db->schema), 'loadTableIndexes');
$reflectionMethod->setAccessible(true);
$indexes = $reflectionMethod->invoke($db->schema, 'user');
print_r($indexes);

What is the expected result?

[
	0 => yii\db\IndexConstraint Object
        (
            [isUnique] => 
            [isPrimary] => 
            [columnNames] => Array
                (
                    [0] => login
                    [1] => name
                )

            [name] => login-name-idx
        ),

	1 => yii\db\IndexConstraint Object
        (
            [isUnique] => 
            [isPrimary] => 
            [columnNames] => Array
                (
                    [0] => name
                    [1] => login
                )

            [name] => name-login-idx
        )
]

What do you get instead?

[
	0 => yii\db\IndexConstraint Object
        (
            [isUnique] => 
            [isPrimary] => 
            [columnNames] => Array
                (
                    [0] => name // <--------------- 
                    [1] => login // <----------------
                )

            [name] => login-name-idx
        ),

	1 => yii\db\IndexConstraint Object
        (
            [isUnique] => 
            [isPrimary] => 
            [columnNames] => Array
                (
                    [0] => name
                    [1] => login
                )

            [name] => name-login-idx
        )
]

Additional info

Q A
Yii version 2.0.15
PHP version 7.1
Operating system win10, ubuntu 12.04
@samdark
Copy link
Member

samdark commented Aug 19, 2018

Why does it matter?

@carono
Copy link
Contributor Author

carono commented Aug 20, 2018

From the perspective of the database, of course the order of the columns in the index is very important.
From the point of view of the framework I'm not sure, I did not find where this function was used.
But there are times when it is necessary to obtain information of a lower level, such as complete information on the indices.

Personally, my special case, I have a package to simplify the work with migrations, there is a function to delete the index by columns, without specifying a name.
For implementation, I started using Schema::loadTableIndexes. In unit tests with postgreSQL produces an error, because the wrong index is deleted.

We can assume that these are my problems, but if such a method already exists, then I think that it should be carried out exactly as I suppose.

_С точки зрения базы данных, разумеется порядок колонок в индексе очень важен.
С точки зрения фреймворка я не уверен, не нашел где бы эта функция использовалась.
Но бывают моменты, когда необходимо получить информацию более низкого уровня, такую как полная информация по индексам.

Лично мой частный случай, у меня есть пакет для упрощения работы с миграциями, там есть фукнция удаления индекса по колонкам, без указания имени.
Для реализации я стал и спользовать Schema::loadTableIndexes. В юнит тестах с postgreSQL выдаёт ошибку, т.к. удаляется не тот индекс.

Можно считать, что это мои проблемы, но если уже существует такой метод, то я думаю, что он должен выполнятся именно так, как я предполагаю._

@samdark
Copy link
Member

samdark commented Aug 20, 2018

OK.

@np25071984
Copy link
Contributor

I don't understand how we can get the index creation time. Suspect it is impossible. As result there isn't way to range indexes according their creation sequence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants