Alembic:如何在模型中迁移自定义类型?

时间:2013-03-27 19:49:51

标签: python sqlalchemy flask-sqlalchemy alembic

我的User型号

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    # noinspection PyShadowingBuiltins
    uuid = Column('uuid', GUID(), default=uuid.uuid4, primary_key=True,
                  unique=True)
    email = Column('email', String, nullable=False, unique=True)
    _password = Column('password', String, nullable=False)
    created_on = Column('created_on', sa.types.DateTime(timezone=True),
                        default=datetime.utcnow())
    last_login = Column('last_login', sa.types.DateTime(timezone=True),
                        onupdate=datetime.utcnow())

其中GUID是自定义类型,如sqlalchemy docs中所述(完全相同)

现在我跑

alembic revision --autogenerate -m "Added initial table"

我的upgrade()

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users',
    sa.Column('uuid', sa.GUID(), nullable=False),
    sa.Column('email', sa.String(), nullable=False),
    sa.Column('password', sa.String(), nullable=False),
    sa.Column('created_on', sa.DateTime(timezone=True), nullable=True),
    sa.Column('last_login', sa.DateTime(timezone=True), nullable=True),
    sa.PrimaryKeyConstraint('uuid'),
    sa.UniqueConstraint('email'),
    sa.UniqueConstraint('uuid')
    )
    ### end Alembic commands ###

但在申请升级期间 - > alembic upgrade head,我看到了

File "alembic/versions/49cc74d0da9d_added_initial_table.py", line 20, in upgrade
    sa.Column('uuid', sa.GUID(), nullable=False),
AttributeError: 'module' object has no attribute 'GUID'

如何在此处使用GUID /自定义类型?

5 个答案:

答案 0 :(得分:7)

根据方言,您可以将sa.GUID()替换为sa.CHAR(32)UUID()(在添加导入行from sqlalchemy.dialects.postgresql import UUID之后)。

GUID()替换它(在添加导入行from your.models.custom_types import GUID之后)也可以使用,但升级脚本与您的模型代码绑定,这可能不是一件好事。

答案 1 :(得分:3)

我遇到了类似的问题并解决了如下问题:

假设您有以下模块my_guid,其中包含(来自您已引用的页面,并进行了少量命名修改):

import uuid as uuid_package
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy import TypeDecorator, CHAR

class GUID(TypeDecorator):
    impl = CHAR

    def load_dialect_impl(self, dialect):
        if dialect.name == 'postgresql':
            return dialect.type_descriptor(PG_UUID())
        else:
            return dialect.type_descriptor(CHAR(32))

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        elif dialect.name == 'postgresql':
            return str(value)
        else:
            if not isinstance(value, uuid_package.UUID):
                return "%.32x" % uuid_package.UUID(value)
            else:
                # hexstring
                return "%.32x" % value

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            return uuid_package.UUID(value)

如果您在模型中使用此GUID,则只需在alembic/env.py处添加三行:

from my_guid import GUID
import sqlalchemy as sa
sa.GUID = GUID

这对我有用。希望有所帮助!

答案 2 :(得分:1)

对于大多数自定义类型,使用__repr__属性类的impl函数对我有用。我发现将迁移定义包含在类中更加清晰,而不是担心将导入放在env.pyscripts.py.mako中。此外,它使您可以轻松地在模块之间移动代码。

Class GUID(types.TypeDecorator)
    impl = CHAR

    def __repr__(self):
        return self.impl.__repr__()

    # You type logic here.

自动迁移将生成CHAR(length=XXX)

答案 3 :(得分:1)

跟进 @Red-Tune-84 的解决方案

class GUID(types.TypeDecorator)
  impl = CHAR

  def __repr__(self):
    return self.impl.__repr__()

  # You type logic here.

确实有效,但您可能需要同时在 env.py 中设置配置 user_module_prefix

例如,对于 context.configure(..., user_module_prefix="sa."),上面的类型将在 alembic 迁移中显示为 sa.CHAR(...)

答案 4 :(得分:0)

我的解决方案使用sqlalchemy_utils.types.uuid.UUIDType,如果您使用的数据库没有CHAR(32)类型,则使用BINARY(16)UUID表示UUID。您需要在迁移中考虑到这一点,迁移必须在没有CHAR(32)/BINARY(16)类型的数据库上创建UUID,并在具有UUIDType类型的数据库上创建。{p>

我的SQLAlchemy类如下:

from sqlalchemy_utils.types.uuid import UUIDType
from sqlalchemy import CHAR, Column, Integer

Base = declarative_base()

def get_uuid():
    return str(uuid.uuid4())

class Dashboard(Base):
    __tablename__ = 'dashboards'
    id = Column(Integer, primary_key=True)
    uuid = Column(UUIDType(binary=False), default=get_uuid)

,实际的批处理操作如下所示(它支持SQLite,MySQL和Postgres):

from superset import db # Sets up a SQLAlchemy connection

def upgrade():
    bind = op.get_bind()
    session = db.Session(bind=bind)
    db_type = session.bind.dialect.name

    def add_uuid_column(col_name, _type):
        """Add a uuid column to a given table"""
        with op.batch_alter_table(col_name) as batch_op:
            batch_op.add_column(Column('uuid', UUIDType(binary=False), default=get_uuid))
        for s in session.query(_type):
            s.uuid = get_uuid()
            session.merge(s)

        if db_type != 'postgresql':
            with op.batch_alter_table(col_name) as batch_op:
                batch_op.alter_column('uuid', existing_type=CHAR(32),
                                      new_column_name='uuid', nullable=False)
                batch_op.create_unique_constraint('uq_uuid', ['uuid'])

        session.commit()

add_uuid_column('dashboards', Dashboard)
session.close()

希望这会有所帮助!