I can't create field of Enum type: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedObject) type "companytype" does not exist

I can't create field of Enum type: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedObject) type "companytype" does not exist

from aenum import Enum

class CompanyType(Enum):
    type1 = 1
    type2 = 2

class Company(BaseModel):

    __tablename__ = 'company'

    company_type = db.Column(db.Enum(CompanyType), default=CompanyType.type1, nullable=False)

奇怪的是我已经有了另一个带有枚举字段的模型并且它工作正常,在数据库本身中创建了变量。但我不记得我当时具体做了什么。 这次我尝试使用 alembic 更新数据库时出现异常。

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedObject) type "companytype" does not exist LINE 1: ALTER TABLE company ADD COLUMN type companytype NOT ... ^

[SQL: ALTER TABLE company ADD COLUMN type companytype NOT NULL] (Background on this error at: http://sqlalche.me/e/13/f405)

Alembic 生成的代码是:

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('company', sa.Column('type', sa.Enum('type1', 'type2', name='companytype'), nullable=True))
    # ### end Alembic commands ###

我觉得我必须说数据库来创建这个变量,但我不知道如何。

更新

我找到了解决方法。原来只有当 table 已经存在时才会出现问题。因此,我创建了一个具有相同列的 temp table,脚本在数据库中生成了枚举变量。然后我删除了 table 并将该列添加到我的公司 table,它终于成功了。不确定,如果它是一个错误,谁的。

您遇到的问题是 bug 在 Alembic 中。目前,当 Enum 已经存在时,您需要手动更改 upgrade 函数以成功升级数据库:

from sqlalchemy.dialects import postgresql

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    companytype_enum = postgresql.ENUM('type1', 'type2', name='companytype', create_type=False)
    companytype_enum.create(op.get_bind(), checkfirst=True)
    op.add_column('company', sa.Column('type', companytype_enum, nullable=True))
    # ### end Alembic commands ###