sql >> データベース >  >> RDS >> PostgreSQL

Alembicを使用して列挙型フィールドを変更する

    私はpostgresのアプローチにできるだけ直接従うことを決心し、次の移行を思いつきました。

    from alembic import op
    import sqlalchemy as sa
    
    old_options = ('nonexistent_executable', 'signal', 'success', 'timed_out')
    new_options = sorted(old_options + ('output_limit_exceeded',))
    
    old_type = sa.Enum(*old_options, name='status')
    new_type = sa.Enum(*new_options, name='status')
    tmp_type = sa.Enum(*new_options, name='_status')
    
    tcr = sa.sql.table('testcaseresult',
                       sa.Column('status', new_type, nullable=False))
    
    
    def upgrade():
        # Create a tempoary "_status" type, convert and drop the "old" type
        tmp_type.create(op.get_bind(), checkfirst=False)
        op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE _status'
                   ' USING status::text::_status')
        old_type.drop(op.get_bind(), checkfirst=False)
        # Create and convert to the "new" status type
        new_type.create(op.get_bind(), checkfirst=False)
        op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE status'
                   ' USING status::text::status')
        tmp_type.drop(op.get_bind(), checkfirst=False)
    
    
    def downgrade():
        # Convert 'output_limit_exceeded' status into 'timed_out'
        op.execute(tcr.update().where(tcr.c.status==u'output_limit_exceeded')
                   .values(status='timed_out'))
        # Create a tempoary "_status" type, convert and drop the "new" type
        tmp_type.create(op.get_bind(), checkfirst=False)
        op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE _status'
                   ' USING status::text::_status')
        new_type.drop(op.get_bind(), checkfirst=False)
        # Create and convert to the "old" status type
        old_type.create(op.get_bind(), checkfirst=False)
        op.execute('ALTER TABLE testcaseresult ALTER COLUMN status TYPE status'
                   ' USING status::text::status')
        tmp_type.drop(op.get_bind(), checkfirst=False)
    

    alembicはUSINGを直接サポートしていないようです alter_tableのステートメント メソッド。



    1. ORA-38868

    2. SQL Server CLR統合は構成ファイルをサポートしていますか?

    3. 高可用性のためにMariaDBクラスター10.5をデプロイする方法

    4. スプリングブートjpahibernateで>4<24の後にDbへの接続が切断される