alembic 实践操作

1. alembic [--config */alembic.ini ] current

2. alembic revision -m "add columns"

    编辑生产的模板文件,更新upgrade/downgrade

  如何编辑见后文。

3. alembic upgrade head[or version]

4. alembic downgrade -1

5. 编写模板文件 修改upgrade downgrade

revision = '...'
down_revision = '...'

from alembic import op
import sqlalchemy as sa

def upgrade():
    pass

def downgrade():
    pass

1)新建table

  op.create_table(
    'account',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('created_at', sa.DateTime(), nullable=True),
    sa.Column('updated_at', sa.DateTime(), nullable=True),
     sa.Column('nickname', sa.String(length=48), nullable=False),
     sa.Column('identityID', sa.String(length=255), nullable=False),
    sa.PrimaryKeyConstraint('id'),
    mysql_ENGINE='InnoDB',
    mysql_DEFAULT_CHARSET='UTF8'
  )

  op.create_unique_constraint(
    "uniq_account0identityID",
    "account", [identityID])
or
  op.create_table(
    'account',
    ......
  sa.UniqueConstraint('identityID',
             name='uniq_account0identityID')
    ......
  )

2)新增column

  op.add_column('account',
           sa.Column('age', sa.Integer(), nullable=False))
or   op.alter_column(
'account', 'age',            new_column_name='sex', existing_type=sa.Integer())

3)重命名table

  op.rename_table('account', 'tb_account')

4)删除table

  op.drop_table('account')

5)创建外键

  op.create_foreign_key(
          "fk_user_address", "address",
          "user", ["user_id"], ["id"])

6)执行sql

    marital_status_column = sa.Column('maritalStatus', sa.Boolean(), default=False)
    op.add_column('account', marital_status_column)
    account = sa.sql.table('baymodel', marital_status_column)
    op.execute(
        account.update().values({'maritalStatus': True})
    ) 

7)sqlalchemy主要types

sa.Integer()
sa.String(length=255)
sa.DateTime()
sa.Text() 
sa.Boolean()

 

 

posted @ 2017-02-08 09:27  开心星  阅读(990)  评论(0编辑  收藏  举报