tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.37k stars 355 forks source link

fix index name #1617

Closed Abdeldjalil-H closed 1 month ago

Abdeldjalil-H commented 1 month ago

Use index_name from class Index to get index name instead of BaseSchemaGenerator._generate_index_name.

Motivation and Context

This allows you to create your custom index class that inherits from Index and override index_name method to set index name.

How Has This Been Tested?

On existing tests.

Checklist:

coveralls commented 1 month ago

Pull Request Test Coverage Report for Build 9135160308

Details


Changes Missing Coverage Covered Lines Changed/Added Lines %
tortoise/indexes.py 1 3 33.33%
<!-- Total: 1 3 33.33% -->
Totals Coverage Status
Change from base Build 9080530396: 0.01%
Covered Lines: 5786
Relevant Lines: 6483

💛 - Coveralls
abondar commented 1 month ago

Is there reason why defining name for Index class doesn't work for you?

Abdeldjalil-H commented 1 month ago

In my case I am using a custom index class:

from tortoise.indexes import Index

class MyCustomIndex(Index):
    PREFIX = "idx"
    def index_name(self, schema_generator: BaseSchemaGenerator, model: models.Model):
        if self.name:
            return self.name

        table_name = model._meta.db_table

        return f"{self.PREFIX}_{table_name}_{'_'.join(self.fields)}".lower()[:64]

Then I wrap all my indexes with this custom class so the name is generated automatically. But when I run the migrations, I still get the old name.

By the way, this is not the case if you pass expressions instead of fields as you can see in the previous code.