sqlalchemy Alembic 学习笔记

前一段时间 一直用sqlalchemy-migrate 这个工具来做migrate,不过感觉不太好用。

今天开始学习Alembic 这个工具,由sqlalchemy 的作者一手开发的。

官方Tutorial:http://alembic.readthedocs.org/en/latest/tutorial.html

一: 安装 

ubuntu@yee:~$ sudo pip install alembic

二、初始化:

ubuntu@yee:~/project$ alembic init alembic
回到project 主目录 :
vim alembic.ini

# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

#sqlalchemy.url = driver://user:pass@localhost/dbname
sqlalchemy.url = mysql://root:*********@localhost:3306/dbname

三、使用

alembic revision -m "create friendship table"
vim alembic/versions/96274508199_create_friendship_table.py
import datetime
def
upgrade(): op.create_table( 'friendship',

          sa.Column('id',sa.Integer,primary_key=True),
          sa.Column('me',sa.Integer,sa.ForeignKey('users.id')),
          sa.Column('friend',sa.Integer,sa.ForeignKey('users.id')),
          sa.Column('created', sa.DateTime, nullable=False,default=datetime.datetime.now()),

          )

def downgrade():
    op.drop_table('friendship')

四、生成表:

alembic upgrade head

 

例二:添加字段:

def upgrade():
    op.add_column('users', sa.Column('created',sa.DateTime,default=datetime.datetime.now(),nullable=False))
    op.add_column( 'users', sa.Column('last_login' ,sa.String(250),nullable=False))
    op.add_column('users', sa.Column('registration_ip' ,sa.String(250),nullable=False))
    op.add_column( 'users', sa.Column('last_login_ip' ,sa.String(250),nullable=False))

def downgrade():
    op.drop_column('users', 'created' )
    op.drop_column('users', 'last_login')
    op.drop_column('users', 'registration_ip')
    op.drop_column('users', 'last_login_ip')
alembic upgrade +1

 

 

posted @ 2012-12-05 11:20  notewo  阅读(2492)  评论(0编辑  收藏  举报