tortoise / tortoise-orm

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

Meta indexes are not created safely #1565

Open rgabor-dev opened 3 months ago

rgabor-dev commented 3 months ago

Describe the bug When creating a PartialIndex with Meta, the index is not created safely nor in the migration file neither with Tortoise.generate_schemas(safe=True). This results a failure when generating schemas.

To Reproduce

Tortoise ORM version: 0.20.0

Creating a test model with indexes:

from tortoise.models import Model
from tortoise.indexes import PartialIndex
from tortoise import fields

class TestModel(Model):
    name = fields.CharField(max_length=255)
    age = fields.IntField(index=True)

    class Meta:
        indexes = [
            PartialIndex(fields=["name"], condition={"name": "admin"}),
        ]

The generated migration:

CREATE TABLE IF NOT EXISTS "testmodel" (
    "id" SERIAL NOT NULL PRIMARY KEY,
    "name" VARCHAR(255) NOT NULL,
    "age" INT NOT NULL
);
CREATE INDEX IF NOT EXISTS "idx_testmodel_age_122507" ON "testmodel" ("age");
CREATE  INDEX "idx_testmodel_name_de9da2" ON "testmodel" ("name") WHERE name = 'admin';

Calling await Tortoise.generate_schemas(safe=True):

tortoise.exceptions.OperationalError: relation "idx_testmodel_name_de9da2" already exists

Expected behavior The index should be created safely using IF NOT EXISTS in the migration and generate_schemas shouldn't fail either when safe is set to True.