tortoise / tortoise/tortoise-orm

Mysql duplicate key error when generate schemas

Open
#1,354 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

Here is the Model class, I used Index(fields="", name="") to custom a index:

class Sources(Model):

    id = fields.BigIntField(pk=True)
    create_time = fields.DatetimeField(null=False, auto_now_add=True)
    update_time = fields.DatetimeField(null=False, auto_now=True)
    name = fields.CharField(32, null=False)

    class Meta:
        table = "sources"
        table_description = "sources_record"
        indexes = [
            Index(fields=("name",), name="idx_source_name")
        ]

    def __str__(self) -> str:
        return self.name

Every time I restart the project, when running at:

await Tortoise.generate_schemas(safe=True)

It will occur an tortoise.exceptions.OperationalError:

tortoise.exceptions.OperationalError: (1061, "Duplicate key name 'idx_source_name'")

When I changed the model creating code to below, there would be no error:

    class Meta:
        table = "sources"
        table_description = "sources_record"
        indexes = [
            ("name", )
        ]

So, is this a bug or a wrong operation? What's the proper code if I want to create a custom index?
Thanks a lot.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the model from the issue with MySQL and await Tortoise.generate_schemas(safe=True), then compare the Index(fields=("name",), name="idx_source_name") form with the tuple form. Trace the schema-generation path used for named indexes and verify that restarting with safe=True does not raise a duplicate-key error; confirm the proper custom-index declaration.

Written by the indexing model from the issue text.

Assessment

Tech stack
mysql, python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.