将SQLAlchemy与Oracle和Flask一起使用,为主键创建序列

2024-04-29 10:41:14 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在Oracle中使用SQLAlchemy时,我还必须为主键添加序列,但是迁移并不是单独创建序列的。我怎样才能得到要创建的序列?在

我已经尝试过多次调整代码来让SQLAlchemy为主键创建oracle序列,但是到目前为止,我还不能获得SQLAlchemy创建的oracle序列。到目前为止,我有一个非常简单的用户/角色设置,表存在,但没有序列。它运行时不会显示错误。在

模型类如下所示:

class Role(SurrogatePK, Model):
    """A role for a user."""

    __tablename__ = 'roles'
    id = db.Column(db.Integer, db.Sequence(__tablename__ + '_id_seq'), primary_key=True)
    name = Column(db.String(80), unique=True, nullable=False)
    user_id = reference_col('users', nullable=True)
    user = relationship('User', backref='roles')

    def __init__(self, name, **kwargs):
        """Create instance."""
        db.Model.__init__(self, name=name, **kwargs)

我用的是烧瓶,炼金术,然后我就跑了

^{pr2}$

我没有看到错误,一切看起来都很好。然而,在我奔跑之后

$ python manage.py db upgrade
INFO  [alembic.runtime.migration] Context impl OracleImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> 61ca5eb70d06, empty message

第一次尝试创建记录时,它失败并显示:

sqlalchemy.exc.DatabaseError 数据库错误:(cx_Oracle.Database错误)ORA-02289:序列不存在

如果我手动创建序列,效果很好。在


Tags: nameinfoidtruedbmodelsqlalchemy错误
1条回答
网友
1楼 · 发布于 2024-04-29 10:41:14

多亏了univerio,我发现alembic不为您处理序列的创建。因此,基于此,我在谷歌上搜索,想出了一个解决方案:

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###

    # not sure of the sequence for creating an object, so just called execute below.
    # op.execute(sa.schema.CreateSequence(sa.Sequence("users_id_seq")))

    op.execute("create sequence roles_id_seq start with 1 increment by 1 nocache nocycle")
    op.execute("create sequence users_id_seq start with 1 increment by 1 nocache nocycle")

对于降级:

^{pr2}$

如您所见,不确定用nocache创建序列的语法是什么,所以我直接调用了SQL。这起作用了,创造了所需的序列。在

相关问题 更多 >