SqlAlchemy迁移声明式

时间:2011-07-22 06:05:03

标签: python orm sqlalchemy pylons pyramid

我已经将SqlAlchemy-Migrate tutorial上的教程修改为我的Pylons Pyramid项目的声明性语法。我可以成功升级和降级,但我关注下面的Base.metadata.drop_all(migrate_engine)命令。这是我的迁移文件:

from sqlalchemy import Column
from sqlalchemy.types import Integer, String, DateTime
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker

from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    email = Column(String(75), unique=True)
    fullname = Column(String(60))          
    password = Column(String(51))          
    last_login = Column(DateTime)          
    date_joined = Column(DateTime, default=func.now())

def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind migrate_engine
    # to your metadata
    Base.metadata.bind = migrate_engine
    Base.metadata.create_all(migrate_engine) # IS THIS DANGEROUS?

def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    Base.metadata.bind = migrate_engine
    Base.metadata.drop_all(migrate_engine) # IS THIS DANGEROUS?

[编辑] 我的问题是如何单独创建表。我不知道这是我的问题,直到提出错误的问题,才能找到正确的问题。

1 个答案:

答案 0 :(得分:7)

升级的正确解决方案是获取表并单独创建它,如下所示:

def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind migrate_engine
    # to your metadata
    User.__table__.create(migrate_engine)

并且,对于降级:

def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    User.__table__.drop(migrate_engine)