tortoise / aerich

A database migrations tool for TortoiseORM, ready to production.
https://github.com/tortoise/aerich
Apache License 2.0
823 stars 93 forks source link

Incorrect index creation order #151

Closed Chise1 closed 3 years ago

Chise1 commented 3 years ago

Now I have a model like this:

class Author(Model):
    name = fields.CharField(max_length=255)

I update it to this:

class Author(Model):
    name = fields.CharField(max_length=255)
    nickname = fields.CharField(max_length=32)
    class Meta:
        unique_together=(("name","nickname"),)

The sql file has an error: It will create unique index before create field.

boh5 commented 3 years ago

I may have encountered the same problem. I have a model like this:

class User(BaseModel):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=128, unique=True, description='名称')
    password_hash = fields.CharField(max_length=128, description='密码哈希')

    metas: fields.ReverseRelation['Meta']

class Meta(BaseModel):
    id = fields.IntField(pk=True)
    clip_title = fields.CharField(max_length=512, description='母本标题')
    user: fields.ForeignKeyRelation['User'] = fields.ForeignKeyField('models.User', related_name='metas')

I have migrated and uupgraded this model. Now, I want to add a field and add a unique key with this field:

class Meta(BaseModel):
    id = fields.IntField(pk=True)
    custom_id = fields.CharField(max_length=128, description='自定义ID')  # add a field
    clip_title = fields.CharField(max_length=512, description='母本标题')
    user: fields.ForeignKeyRelation['User'] = fields.ForeignKeyField('models.User', related_name='metas')

    class Meta:
        unique_together = ('custom_id', 'user')   # add unique key with new field

The SQL generated by aerich is:

-- upgrade --
ALTER TABLE `meta` ADD `custom_id` VARCHAR(128) NOT NULL  COMMENT '自定义ID';
ALTER TABLE `meta` ADD UNIQUE INDEX `uid_meta_custom__2e5d62` (`custom_id`, `user_id`);
-- downgrade --
ALTER TABLE `meta` DROP INDEX `uid_meta_custom__2e5d62`;
ALTER TABLE `meta` DROP COLUMN `custom_id`;

The order of sql is not correct, so upgrade cannot be applied.

long2ice commented 3 years ago

Fixed