开发者

SqlAlchemy Migrate Declarative

开发者 https://www.devze.com 2023-03-22 07:59 出处:网络
I\'ve modified the tutorial on the SqlAlchemy-Migrate tutorial to declarative syntax for my Pylons Pyramid project. I can successfully upgrade and downgrade, but I\'m concerned about the Base.metadata

I've modified the tutorial on the SqlAlchemy-Migrate tutorial to declarative syntax for my Pylons Pyramid project. I can successfully upgrade and downgrade, but I'm concerned about the Base.metadata.drop_all(migrate_engine) command below. Here is my migration file:

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 ow开发者_如何学Cn 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?

[edit] My question was how to individually create tables. I didn't know this was my question until asking the wrong question enough, to get to the correct question.


The proper solution on upgrade is to get the table and create it individually, like such:

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)

and, for downgrading:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号