tortoise / aerich

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

FK column rename error #325

Open Prof1-web opened 6 months ago

Prof1-web commented 6 months ago

Aerich 0.7.2, PostgreSQL 15.3

Example:

class User(Model):
    id = fields.BigIntField(pk=True)

class Client(Model):
    id = fields.BigIntField(pk=True)
    user = fields.ForeignKeyField("models.User")

Aerich generate:

CREATE TABLE IF NOT EXISTS "user" (
    "id" BIGSERIAL NOT NULL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS "client" (
    "id" BIGSERIAL NOT NULL PRIMARY KEY,
    "user_id" BIGINT NOT NULL REFERENCES "user" ("id") ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS "aerich" (
    "id" SERIAL NOT NULL PRIMARY KEY,
    "version" VARCHAR(255) NOT NULL,
    "app" VARCHAR(100) NOT NULL,
    "content" JSONB NOT NULL
);

Then I changed fk_column name and ran migrate:

class Client(Model):
    id = fields.BigIntField(pk=True)
    user_new_name = fields.ForeignKeyField("models.User")

Aerich generate:

ALTER TABLE "client" DROP CONSTRAINT "fk_client_user_f9356948";
ALTER TABLE "client" RENAME COLUMN "user_id" TO "user_new_name_id";
ALTER TABLE "client" ADD CONSTRAINT "fk_client_user_66c1dc3d" FOREIGN KEY ("user_new_name_id") REFERENCES "user" ("id") ON DELETE CASCADE;

And it can't perform this migration. Because CONSTRAINT "fk_client_user_f9356948" does not exist.

And why is aerich removing the constraint? DB can rename it without removing the constraint. Removing and adding can be a problem for large tables