How can I convert a MySQL table to utf8 character set using alembic?

My database is MySQL. I am using SqlAlchemy ORM to define and access it. I am using Alembic for migration. I have a model with a box that only used English text (Ascii / latin-1). This field should now contain Unicode text. To convert my model to Unicode support for MySQL I need to add the following class level attribute: mysql_character_set = 'utf8'

class MyModel(Base):
    __tablename__ = 'mymodel'
    mysql_character_set = 'utf8'

    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)

      

So far so good. I want to add this attribute as part of the Alembic migration script. I usually use Alembic's excellent automatic command:

alembic revision --autogenerate

      

The problem is that this command does not commit every change to the model, and in particular does not add the mysql_character_set attribute .

How do I add this attribute manually to alembic script migration?

+3


source to share


1 answer


I did it like this:



from alembic import op
import sqlalchemy as sa


def upgrade():
    conn = op.get_bind()
    conn.execute(sa.sql.text('ALTER table my_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci'))

      

+1


source







All Articles