0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pyramidフレームワークで作成したプロジェクトに、alembicを追加する。(スキーマ管理)

Posted at

pyramidのSQLAlchemyでプロジェクトを作成しておくこと
作成されたプロジェクトは、今回はhelloという名前でプロジェクト作成している
ここで作成したものに追加した例です

仮想環境

source env3/bin/activate

alembicのインストール

pip install alembic

alembic用のiniファイルを作成

alembicコマンドで、初期化します。
今回は、mydbというディレクトリを作成に初期化したものを入れます。(第二引数)

cd hello
alembic init mydb

DBへの接続用文字列を変更

vi alembic.ini

develop.iniを見ると、

sqlalchemy.url = sqlite:///%(here)s/hello.sqlite

のように書いてあるので、それで上書きします。

一番初めのalembicファイルを作成

alembic -c alembic.ini revision -m "initial"

こんな内容のファイルが作成されます。
スキーマ管理用のファイルで、upgradeはバージョンを上げた場合、downgradeはバージョンを下げた場合の挙動を記述します。

def upgrade():
    pass


def downgrade():
    pass

たとえば、テーブルの作成を例に作成します。

"""create table store

Revision ID: XXXX
Revises: YYYY
Create Date: 2019-04-13 12:23:59.707962

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql.expression import text
from sqlalchemy.sql import functions as sqlf

Identifier = sa.BigInteger

# revision identifiers, used by Alembic.
revision = 'XXXX'
down_revision = 'YYYY'
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        'Store',
        sa.Column('id', Identifier, primary_key=True),
        sa.Column('name', sa.Unicode(length=255), nullable=False, index=True),
        sa.Column('tel', sa.Unicode(length=13), nullable=False, index=True),
        sa.PrimaryKeyConstraint('id')
    )


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

スキーマファイルを適用します

これでupgradeが動き、テーブルが作成されています。

alembic -c alembic.ini upgrade head

スキーマファイルの適用を戻す

リリースなどで失敗して戻したい場合は、以下のように戻します。
これでdowngradeが動き、テーブルが削除されます

alembic -c alembic.ini downgrade -1

スキーマファイル追加

初回に追加したのを積み重ねていくことで、スキーマを管理します。

alembic -c alembic.ini revision -m "schema description"

alembicの過去履歴を見る

alembic -c alembic.ini history

mysqlにつなぐ場合

ユーザ名:test
パスワード:test
DB名:test

sqlalchemy.url = mysql+pymysql://test:test@127.0.0.1/test?use_unicode=true&charset=utf8
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?