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

nyc*_*nik 0 python oracle sqlalchemy flask flask-sqlalchemy

当我将 SQLAlchemy 与 Oracle 结合使用时,我还必须为主键添加序列,但迁移不会自行创建序列。如何获得要创建的序列?

我曾多次尝试调整代码以使 SQLAlchemy 为主键创建 oracle 序列,但到目前为止,我还无法获得由 SQLAlchemy 创建的 Oracle 序列。到目前为止,我有一个非常简单的用户/角色设置,并且存在表,但不存在序列。它运行时没有显示任何错误。

Model 类如下所示:

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

我正在使用 Flask 和 SQLAlchemy,并且在我运行之后;

$ python manage.py db init
Creating directory <lots removed here>...done

$ $ python manage.py db migrate
INFO  [alembic.runtime.migration] Context impl OracleImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate.compare] Detected added table 'users'
INFO  [alembic.autogenerate.compare] Detected added table 'roles'
Run Code Online (Sandbox Code Playgroud)

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

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

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

sqlalchemy.exc.DatabaseError DatabaseError: (cx_Oracle.DatabaseError) ORA-02289: 序列不存在

如果我手动创建序列,它工作正常。

nyc*_*nik 5

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

和降级:

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.execute(sa.schema.DropSequence(sa.Sequence("roles_id_seq")))
    op.execute(sa.schema.DropSequence(sa.Sequence("users_id_seq")))
Run Code Online (Sandbox Code Playgroud)

如您所见,不确定使用 nocache 创建序列的语法是什么,所以我直接调用了 SQL。这行得通,并创建了所需的序列。