我无法创建枚举类型的字段:sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedObject) 类型“companytype”不存在

mim*_*mic 5 postgresql sqlalchemy alembic

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)
Run Code Online (Sandbox Code Playgroud)

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

sqlalchemy.exc.ProgrammingError:(psycopg2.errors.UndefinedObject)类型“companytype”不存在第1行:ALTER TABLE company ADD COLUMN type companytype NOT ... ^

[SQL: ALTER TABLE company ADD COLUMN type companytype NOT NULL](此错误的背景位于: 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 ###
Run Code Online (Sandbox Code Playgroud)

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

更新

我找到了一个解决方法。事实证明,只有当表已经存在时才会出现该问题。因此,我创建了一个具有相同列的临时表,并且脚本在数据库中生成了枚举变量。然后我删除了该表并将该列添加到我的公司表中,它终于起作用了。不确定这是否是一个错误,以及是谁的错误。

rfk*_*aas 10

您遇到的问题是 Alembic 中的一个错误。目前,upgrade当数据库已经存在时,您需要手动更改函数才能成功升级数据库Enum

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 ###
Run Code Online (Sandbox Code Playgroud)